/*
 * Copyright (C) 2010 mAPPn.Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mol.market.common.network;

import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.net.Uri;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.text.style.ForegroundColorSpan;
import com.mol.market.Constants;
import com.mol.market.R;
import com.mol.market.Session;
import com.mol.market.common.codec.binary.Base64;
import com.mol.market.common.util.*;
import com.mol.market.common.vo.*;
import com.mol.market.demo.widget.CornerMark;
import com.mol.market.fanli.ui.TaskInformationActivity.RebateTask;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParserException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;

/**
 * API 响应结果解析工厂类，所有的API响应结果解析需要在此完成。
 *
 * @author andrew
 * @date 2011-4-22
 */
public final class ApiResponseFactory {

    // private static final String TAG = "ApiResponseFactory";

    private ApiResponseFactory() {

    }

    /**
     * 解析市场API响应结果
     *
     * @return 解析后的结果（如果解析错误会返回Null）
     */

    public static Object parse(Context context, ApiResponse response) {

        InputStream in = response.content;
//    String inputBody = null;
//    if (MarketAPI.ACTION_GET_ALIPAY_ORDER_INFO == action
//        || MarketAPI.ACTION_QUERY_ALIPAY_RESULT == action
//        || MarketAPI.ACTION_GET_SEARCH_RECOMMEND == action) {
//      inputBody = Utils.getStringResponse(response);
//      if (TextUtils.isEmpty(inputBody)) {
//        return null;
//      }
//    } else if (MarketAPI.ACTION_CHECK_LOG_LEVEL == action
//        || MarketAPI.ACTION_INSERT_LOG == action) {
//      inputBody = Utils.getGzipStringResponse(response);
//      if (TextUtils.isEmpty(inputBody)) {
//        return null;
//      }
//    } else {
//      in = Utils.getInputStreamResponse(response);
//      if (in == null) {
//        return null;
//      }
//    }
//
        String requestMethod = "";
        Object result = null;
        try {
        	if(response.action == MarketAPI.ACTION_GET_CATEGORY) {
        		System.out.println("");
        	}
            switch (response.action) {

                case MarketAPI.ACTION_REGISTER:

                    // 注册
                    requestMethod = "ACTION_REGISTER";
                    result = parseLoginOrRegisterResult(XmlElement.parseXml(in));
                    break;

                case MarketAPI.ACTION_LOGIN:

                    // 登录
                    requestMethod = "ACTION_LOGIN";
                    result = parseLoginOrRegisterResult(XmlElement.parseXml(in));
                    break;
                    
                case MarketAPI.ACTION_THRID_LOGIN:
                	requestMethod = "ACTION_THRID_LOGIN";
                    result = parseThirdLoginResult(XmlElement.parseXml(in));
                    break;

                case MarketAPI.ACTION_GET_TOP_RECOMMEND:

                    // 获取首页顶部推荐
                    requestMethod = "ACTION_GET_TOP_RECOMMEND";
                    result = parseTopRecommend(XmlElement.parseXml(in));
                    break;

                case MarketAPI.ACTION_GET_HOME_RECOMMEND:

                    // 获取首页推荐
                    requestMethod = "ACTION_GET_HOME_RECOMMEND";
                    result = parseProductList(context, XmlElement.parseXml(in), true);
                    break;
                case MarketAPI.ACTION_GET_HISTORY_INSTALL:
                	requestMethod = "ACTION_GET_HISTORY_INSTALL";
                    result = parseProductList(context, XmlElement.parseXml(in), false);
                	break;
                case MarketAPI.ACTION_INSERT_HISTORY_INSTALL:
                	requestMethod = "ACTION_INSERT_HISTORY_INSTALL";
                	// ====================================================
                    result = parseProductList(context, XmlElement.parseXml(in), true);
                	break;
                case MarketAPI.ACTION_GET_SEARCH_KEYWORDS:

                    // 获取搜索热词
                    requestMethod = "ACTION_GET_SEARCH_KEYWORDS";
                    result = parseSearchKeywords(context, XmlElement.parseXml(in));
                    break;

                case MarketAPI.ACTION_GET_COMMENTS:

                    // 获取评论列表
                    requestMethod = "ACTION_GET_COMMENTS";
                    result = parseComments(XmlElement.parseXml(in));
                    break;

                case MarketAPI.ACTION_GET_MYRATING:

                    // 获取我的评级
                    requestMethod = "ACTION_GET_MYRATING";
                    result = parseMyRating(XmlElement.parseXml(in));
                    break;

                case MarketAPI.ACTION_ADD_RATING:

                    // 添加评级
                    requestMethod = "ACTION_ADD_RATIONG";
                    result = true;
                    break;

                case MarketAPI.ACTION_ADD_COMMENT:

                    // 添加评论
                    requestMethod = "ACTION_ADD_COMMENT";
                    result = parsePostComment(context, XmlElement.parseXml(in));
                    break;

                case MarketAPI.ACTION_GET_PRODUCT_DETAIL:

                    // 获取应用详细
                    requestMethod = "ACTION_GET_PRODUCT_DETAIL";
                    result = parseProductDetail(XmlElement.parseXml(in));
                    break;

                case MarketAPI.ACTION_GET_RANK_BY_CATEGORY:

                    // 获取排行列表
                    requestMethod = "ACTION_GET_RANK_BY_CATEGORY";
                    result = parseProductList(context, XmlElement.parseXml(in), false);
                    break;

                case MarketAPI.ACTION_GET_GROW_FAST:

                    // 获取增长最快排行
                    requestMethod = "ACTION_GET_GROW_FAST";
                    result = parseProductList(context, XmlElement.parseXml(in), false);
                    break;

                case MarketAPI.ACTION_PAID_RANK:

                    // 获取收费排行榜
                    requestMethod = "ACTION_PAID_RANK";
                    result = parseProductList(context, XmlElement.parseXml(in), false);
                    break;

                case MarketAPI.ACTION_GET_DETAIL:

                    // 获取产品详细信息
                    requestMethod = "ACTION_GET_DETAIL";
                    result = parseProductDetail(XmlElement.parseXml(in));
                    break;

                case MarketAPI.ACTION_SYNC_BUYLOG:

                    // 获取消费记录
                    requestMethod = "ACTION_SYNC_BUYLOG";
                    result = parseSyncBuyLog(context, XmlElement.parseXml(in));
                    break;

                case MarketAPI.ACTION_SYNC_APPS:

                    // 提交安装应用信息
                    requestMethod = "ACTION_SYNC_APPS";
                    result = parseSyncApps(XmlElement.parseXml(in));
                    break;

                case MarketAPI.ACTION_CHECK_NEW_VERSION:

                    // 检查应用版本
                    requestMethod = "ACTION_CHECK_NEW_VERSION";
                    result = parseCheckNewVersion(context, XmlElement.parseXml(in));
                    break;

                case MarketAPI.ACTION_PURCHASE_PRODUCT:

                    // 购买应用
                    requestMethod = "ACTION_PURCHASE_PRODUCT";
                    result = true;
                    break;

                case MarketAPI.ACTION_GET_DOWNLOAD_URL:

                    // 获得下载链接地址
                    requestMethod = "ACTION_GET_DOWNLOAD_URL";
                    result = parseDownloadInfo(XmlElement.parseXml(in));
                    break;

                case MarketAPI.ACTION_GET_ALL_CATEGORY:
                case MarketAPI.ACTION_GET_CATEGORY:
                    // 获得全部分类
                    requestMethod = "ACTION_GET_ALL_CATEGORY";
                    result = parseAllCategory(XmlElement.parseXml(in));
                    break;

                case MarketAPI.ACTION_GET_PRODUCTS:

                    // 获得分类产品列表
                    requestMethod = "ACTION_GET_PRODUCTS";
                    result = parseProductList(context, XmlElement.parseXml(in), false);
                    break;

                case MarketAPI.ACTION_GET_RECOMMEND_PRODUCTS:

                    // 获得专题推荐产品列表
                    requestMethod = "ACTION_GET_RECOMMEND_PRODUCTS";
                    result = parseProductList(context, XmlElement.parseXml(in), false);
                    break;

                case MarketAPI.ACTION_BBS_SEARCH:

                    // 获得BBS附件搜索列表
                    requestMethod = "ACTION_BBS_SEARCH";
                    String searchResult = new BufferedReader(new InputStreamReader(in))
                        .readLine();
                    result = parseBbsSearchResult(searchResult);
                    break;

                case MarketAPI.ACTION_SEARCH:

                    // 获得BBS附件搜索列表
                    requestMethod = "ACTION_SEARCH";
                    result = parseProductList(context, XmlElement.parseXml(in), false);
                    break;

                case MarketAPI.ACTION_GET_REQUIRED:

                    // 装机必备
                    requestMethod = "ACTION_GET_REQUIRED";
                    result = parseGetRequired(context, XmlElement.parseXml(in));
                    break;

                case MarketAPI.ACTION_GET_TOPIC:

                    // 获得专题列表
                    requestMethod = "ACTION_GET_TOPIC";
                    result = parseTopicList(context, XmlElement.parseXml(in));
                    break;

                case MarketAPI.ACTION_CHECK_UPGRADE:

                    // 检查应用更新
                    requestMethod = "ACTION_CHECK_UPGRADE";
                    result = parseUpgrade(context, XmlElement.parseXml(in));
                    break;

                case MarketAPI.ACTION_CHECK_NEW_SPLASH:

                    // 检查应用更新
                    requestMethod = "ACTION_CHECK_NEW_SPLASH";
                    result = parseNewSplash(XmlElement.parseXml(in));
                    break;

                case MarketAPI.ACTION_GET_PAY_LOG:

                    // 获取购买历史信息列表
                    requestMethod = "ACTION_GET_PAY_LOG";
                    result = parseGetPayLog(context, XmlElement.parseXml(in));
                    break;

                case MarketAPI.ACTION_BIND_ACCOUNT:

                    // 绑定用户手机
                    requestMethod = "ACTION_BIND_ACCOUNT";
                    result = true;
                    break;

                case MarketAPI.ACTION_SYNC_CARDINFO:

                    // 同步充值卡信息
                    requestMethod = "ACTION_SYNC_CARDINFO";
                    result = parseSyncCardinfo(context, XmlElement.parseXml(in));
                    break;

                case MarketAPI.ACTION_CHARGE:

                    // 查询充值结果
                    requestMethod = "ACTION_CHARGE";
                    result = parseChargeResult(XmlElement.parseXml(in));
                    break;

                case MarketAPI.ACTION_QUERY_CHARGE_BY_ORDERID:

                    // 查询充值结果
                    requestMethod = "ACTION_QUERY_CHARGE_BY_ORDERID";
                    result = parseQueryChargeResultByOderID(XmlElement.parseXml(in));
                    break;

                case MarketAPI.ACTION_GET_BALANCE:

                    // 查询余额
                    requestMethod = "ACTION_GET_BALANCE";
                    result = parseGetBalance(XmlElement.parseXml(in));
                    break;

                case MarketAPI.ACTION_GET_ALIPAY_ORDER_INFO: {

                    // 解析支付宝订单结果
                    requestMethod = "ACTION_GET_ALIPAY_ORDER_INFO";
                    String body = Utils.convertToString(response.content,
                        response.charset);
                    result = parseGetAlipayOrderInfo(body);
                    break;
                }

                case MarketAPI.ACTION_QUERY_ALIPAY_RESULT: {

                    // 解析支付宝结果
                    requestMethod = "ACTION_QUERY_ALIPAY_RESULT";
                    String body = Utils.convertToString(response.content,
                        response.charset);
                    result = parseGetAlipayOrderInfo(body);
                    break;
                }

                case MarketAPI.ACTION_UNBIND:

                    // 解除绑定
                    requestMethod = "ACTION_UNBIND";
                    result = true;
                    break;

                case MarketAPI.ACTION_CHECK_LOG_LEVEL: {

                    // 检查Log提交级别
                    requestMethod = "ACTION_CHECK_LOG_LEVEL";
                    String body = Utils.convertToString(response.content,
                        response.charset);
                    result = parseLogLevel(body);
                    break;
                }

                case MarketAPI.ACTION_INSERT_LOG: {

                    // 提交Log
                    requestMethod = "ACTION_INSERT_LOG";
                    String body = Utils.convertToString(response.content,
                        response.charset);
                    result = parseSubmitLog(body);
                    break;
                }

                case MarketAPI.ACTION_GET_MASTER_RECOMMEND:

                    // 获取玩家推荐列表
                    requestMethod = "ACTION_GET_MASTER_RECOMMEND";
                    result = parseMasterRecommend(context, XmlElement.parseXml(in));
                    break;

                case MarketAPI.ACTION_GET_MASTER_RECOMMEND_APPS:

                    // 获取玩家推荐应用
                    requestMethod = "ACTION_GET_MASTER_RECOMMEND_APPS";
                    result = parseProductList(context, XmlElement.parseXml(in), false);
                    break;

                case MarketAPI.ACTION_GET_DISCUSS:

                    // 获取玩家推荐讨论列表
                    requestMethod = "ACTION_GET_DISCUSS";
                    result = parseGetDiscuss(XmlElement.parseXml(in));
                    break;

                case MarketAPI.ACTION_ADD_DISCUSS:

                    // 添加玩家推荐讨论
                    requestMethod = "ACTION_ADD_DISCUSS";
                    result = parsePostComment(context, XmlElement.parseXml(in));
                    break;

                case MarketAPI.ACTION_ADD_RECOMMEND_RATING:

                    // 添加玩家推荐评级
                    requestMethod = "ACTION_ADD_RECOMMEND_RATING";
                    result = true;
                    break;

                case MarketAPI.ACTION_GET_RECOMMEND_RATING:

                    // 获取玩家推荐评级
                    requestMethod = "ACTION_GET_RECOMMEND_RATING";
                    result = parseRecommendRating(XmlElement.parseXml(in));
                    break;

                case MarketAPI.ACTION_DOWN_REPORT:

                    // 添加下载日志
                    requestMethod = "ACTION_DOWN_REPORT";
                    result = true;
                    break;

                case MarketAPI.ACTION_GET_RECOMMEND_NOTIFICATION:

                    // 通知栏精品应用推荐
                    requestMethod = "ACTION_GET_RECOMMEND_NOTIFICATION";
                    result = parseNotificationRecommend(context, XmlElement.parseXml(in));
                    break;

                case MarketAPI.ACTION_GET_MASTER_CONTAINS:

                    // 详细页收录应用达人
                    requestMethod = "ACTION_GET_MASTER_CONTAINS";
                    result = parseMasterContains(context, XmlElement.parseXml(in));
                    break;

                case MarketAPI.ACTION_GET_RECOMMEND_BY_APP:

                    // 更多相关应用
                    requestMethod = "ACTION_GET_RECOMMEND_BY_APP";
                    result = parseProductList(context, XmlElement.parseXml(in), true);
                    break;

                case MarketAPI.ACTION_FOLLOW_MASTER:

                    // 关注达人推荐专题
                    requestMethod = "ACTION_FOLLOW_MASTER";
                    result = parseFllowResult(XmlElement.parseXml(in));
                    break;

                case MarketAPI.ACTION_GET_FOLLOWED_RECOMMEND:

                    // 获取关注达人的推荐
                    requestMethod = "ACTION_GET_FOLLOWED_RECOMMEND";
                    result = parseFllowedRecommend(context, XmlElement.parseXml(in));
                    break;

                case MarketAPI.ACTION_GET_HOME_MASTER_RECOMMEND:

                    // 获取首页玩家推荐列表
                    requestMethod = "ACTION_GET_HOME_MASTER_RECOMMEND";
                    result = parseHomeMasterRecommend(context, XmlElement.parseXml(in));
                    break;

                case MarketAPI.ACTION_MARK_READ:

                    // 标记达人推荐的新应用已读
                    requestMethod = "ACTION_MARK_READ";
                    result = parseMarkAsRead(XmlElement.parseXml(in));
                    break;

                case MarketAPI.ACTION_IFTTT_REPORT:

                    // IFTTT回报
                    requestMethod = "ACTION_IFTTT_REPORT";
                    result = true;
                    break;

                case MarketAPI.ACTION_GET_MESSAGE:

                    // 推送消息
                    requestMethod = "ACTION_GET_MESSAGE";
                    result = parsePushMessage(context, XmlElement.parseXml(in));
                    break;

                case MarketAPI.ACTION_GET_SEARCH_RECOMMEND: {

                    // 搜索推荐
                    requestMethod = "ACTION_GET_SEARCH_RECOMMEND";
                    String body = Utils.convertToString(response.content,
                        response.charset);
                    result = parseSearchRecommend(body);
                    break;

                }

                case MarketAPI.ACTION_GET_EXCHANGE_BALANCE:

                    // 获取返利余额
                    requestMethod = "ACTION_GET_EXCHANGE_BALANCE";
                    result = parseGetExchangeBalance(XmlElement.parseXml(in));
                    break;

                case MarketAPI.ACTION_GET_EXCHANGE_BANNER:

                    // 获取返利首页推广图
                    requestMethod = "ACTION_GET_EXCHANGE_BANNER";
                    result = parseBanners(XmlElement.parseXml(in));
                    break;

                case MarketAPI.ACTION_GET_EXCHANGE_HOME_TASK:

                    // 获取返利首页任务列表
                    requestMethod = "ACTION_GET_EXCHANGE_HOME_TASK";
                    result = parseTasks(context, XmlElement.parseXml(in));
                    break;

                case MarketAPI.ACTION_GET_EXCHANGE_TASK_DETAIL:

                    // 获取返利任务详细
                    requestMethod = "ACTION_GET_EXCHANGE_TASK_DETAIL";
                    result = parseTaskDetail(XmlElement.parseXml(in));
                    break;

                case MarketAPI.ACTION_GET_EXCHANGE_TYPE:

                    // 获取返利兑换类型
                    requestMethod = "ACTION_GET_EXCHANGE_TASK_DETAIL";
                    result = parseExchangeType(context, XmlElement.parseXml(in));
                    break;

                case MarketAPI.ACTION_GET_EXCHANGE_GOODS:

                    // 获取返利兑换物品
                    requestMethod = "ACTION_GET_EXCHANGE_GOODS";
                    result = parseExchangeGoods(context, XmlElement.parseXml(in));
                    break;

                case MarketAPI.ACTION_GET_EXCHANGE_DETAIL:

                    // 获取返利兑换记录明细
                    requestMethod = "ACTION_GET_EXCHANGE_DETAIL";
                    result = parseExchangeDetail(context, XmlElement.parseXml(in));
                    break;

                case MarketAPI.ACTION_GET_EXCHANGE_REWARD:

                    // 获取返利收入明细
                    requestMethod = "ACTION_GET_EXCHANGE_REWARD";
                    result = parseRewardDetail(context, XmlElement.parseXml(in));
                    break;

                case MarketAPI.ACTION_EXCHANGE:

                    // 返利兑换
                    requestMethod = "ACTION_EXCHANGE";
                    result = parseReward(XmlElement.parseXml(in));
                    break;

                case MarketAPI.ACTION_REPORT_INSTALLATION:

                    // 报告安装
                    requestMethod = "ACTION_REPORT_INSTALLATION";
                    result = true;
                    break;

                case MarketAPI.ACTION_REQUEST_REWARD:

                    // 申请返利
                    requestMethod = "ACTION_REQUEST_REWARD";
                    result = parseRequestReward(XmlElement.parseXml(in));
                    break;

                case MarketAPI.ACTION_GET_CATEGORY_TAGS:

                    // 标签列表
                    requestMethod = "ACTION_GET_CATEGORY_TAGS";
                    result = parseCategoryTags(context, XmlElement.parseXml(in));
                    break;

                case MarketAPI.ACTION_GET_TAGS_DETAILS:

                    // 标签详情
                    requestMethod = "ACTION_GET_TAGS_DETAILS";
                    result = parseTagsDetail(context, XmlElement.parseXml(in));
                    break;

                case MarketAPI.ACTION_GET_TAGS_IN_DETAILS:

                    // 详细列表页的标签
                    requestMethod = "ACTION_GET_TAGS_IN_DETAILS";
                    result = parseTagsInDetail(context, XmlElement.parseXml(in));
                    break;

                case MarketAPI.ACTION_RECOMMEND_BY_USER:

                    // 猜你喜欢
                    requestMethod = "ACTION_RECOMMEND_BY_USER";
                    result = parseProductList(context, XmlElement.parseXml(in), true);
                    break;

                default:
                    break;
            }

        } catch (XmlPullParserException e) {
            Utils.D(requestMethod + " has XmlPullParserException", e);
        } catch (IOException e) {
            Utils.D(requestMethod + " has IOException", e);
        } catch (JSONException e) {
            Utils.D(requestMethod + " has JSONException", e);
        } catch (Exception e) {
            Utils.D(requestMethod + " has other unknown Exception", e);
        } finally {
            Utils.closeStreamSilently(in);
        }
        if (result != null) {
            Utils.D(requestMethod + "'s Response is : " + result.toString());
        } else {
            Utils.D(requestMethod + "'s Response is null");
        }
        return result;
    }

    /**
     * 解析发送评论的结果
     */

    private static String parsePostComment(Context ctx, XmlElement
        xmlDocument) {

        if (xmlDocument == null) {
            return null;
        }

        XmlElement hint = xmlDocument.getChild("hint", 0);
        if (hint == null) {
            return ctx.getString(R.string.alert_post_ok);
        }

        String msg = hint.getText();
        if (TextUtils.isEmpty(msg)) {
            return ctx.getString(R.string.alert_post_ok);
        }
        return msg;
    }

    /**
     * 解析返利账户余额
     */

    private static String parseGetExchangeBalance(XmlElement xmlDocument) {

        if (xmlDocument == null) {
            return null;
        }

        XmlElement balance = xmlDocument.getChild("balance", 0);
        if (balance == null) {
            return null;
        }
        return balance.getText();
    }

    /**
     * 解析返利推广图列表
     */

    private static ArrayList<HashMap<String, Object>> parseBanners(
        XmlElement xmlDocument) {

        if (xmlDocument == null) {
            return null;
        }

        XmlElement root = xmlDocument.getChild("tasks", 0);
        if (root == null) {
            return null;
        }
        List<XmlElement> result = root.getChildren("task");

        ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
        for (XmlElement element : result) {
            HashMap<String, Object> item = new HashMap<String, Object>();
            item.put(Constants.KEY_ID, element.getAttribute(Constants.KEY_ID));
            item.put(Constants.KEY_PRODUCT_NAME,
                element.getAttribute(Constants.KEY_PRODUCT_NAME));
            item.put(Constants.KEY_BANNER,
                element.getAttribute(Constants.KEY_BANNER));
            list.add(item);
        }
        return list;
    }

    /**
     * 解析返利平台首页任务列表。
     * <p/>
     * KEY :
     * Constants.KEY_TOTAL_SIZE 列表的总长度
     * Constants.KEY_TASK_LIST  从服务器返回的列表内容
     */

    private static HashMap<String, Object> parseTasks(Context context,
        XmlElement xmlDocument) {

        if (xmlDocument == null) {
            return null;
        }

        HashMap<String, Object> result = new HashMap<String, Object>();
        XmlElement root = xmlDocument.getChild("tasks", 0);
        result.put(Constants.KEY_TOTAL_SIZE,
            Utils.getInt(root.getAttribute(Constants.KEY_TOTAL_SIZE)));

        List<XmlElement> taskListNode = root.getChildren("task");
        if (taskListNode == null) {
            return null;
        }

        ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
        for (XmlElement element : taskListNode) {
            HashMap<String, Object> item = new HashMap<String, Object>();
            item.put(Constants.KEY_PRODUCT_ID,
                element.getAttribute(Constants.KEY_PRODUCT_ID));
            item.put(Constants.KEY_ID,
                element.getAttribute(Constants.KEY_ID));
            item.put(Constants.KEY_PRODUCT_NAME,
                element.getAttribute(Constants.KEY_PRODUCT_NAME));
            item.put(Constants.KEY_PRODUCT_PACKAGE_NAME,
                element.getAttribute(Constants.KEY_PACKAGE));

            String money = Utils.convertCentToYuan(
                element.getAttribute(Constants.KEY_PAY));

            item.put(Constants.KEY_PRODUCT_SIZE,
                Utils.formatByColor(
                    money,
                    context.getString(R.string.rebate_money),
                    context.getResources().getColor(R.color.color_red)));

            item.put(Constants.KEY_PRODUCT_ICON_URL,
                element.getAttribute(Constants.KEY_ICON));
            item.put(Constants.KEY_PRODUCT_SUB_CATEGORY,
                element.getAttribute(Constants.KEY_TYPE));
            item.put(Constants.KEY_REBATE_FLAG,
                Utils.getInt(element.getAttribute(Constants.KEY_STATUS)));
            list.add(item);
        }
        result.put(Constants.KEY_TASK_LIST, list);
        return result;
    }

    /**
     * 解析返利任务详细信息
     */

    private static RebateTask parseTaskDetail(XmlElement xmlDocument) {

        if (xmlDocument == null) {
            return null;
        }

        XmlElement element = xmlDocument.getChild("task", 0);
        if (element == null) {
            return null;
        }

        RebateTask task = new RebateTask();
        task.taskId = element.getAttribute(Constants.KEY_PRODUCT_ID);
        task.taskName = element.getAttribute(Constants.KEY_PRODUCT_NAME);
        task.iconUrl = element.getAttribute(Constants.KEY_ICON);
        task.taskType = element.getAttribute(Constants.KEY_TYPE);
        task.rebateMoney = Utils.getInt(element.getAttribute(Constants.KEY_PAY));
        task.bannerUrl = element.getAttribute(Constants.KEY_IMAGE);
        task.description = element.getAttribute(Constants.KEY_DESCRIPTION);
        task.status = Utils.getInt(element.getAttribute(Constants.KEY_STATUS));
        task.pkgName = element.getAttribute(Constants.KEY_PACKAGE);
        return task;
    }

    /**
     * 解析兑换类型列表
     */

    private static ArrayList<HashMap<String, Object>> parseExchangeType(
        Context context, XmlElement xmlDocument) {

        if (xmlDocument == null) {
            return null;
        }

        XmlElement root = xmlDocument.getChild("types", 0);
        List<XmlElement> typeList = root.getChildren("type");

        ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
        for (XmlElement element : typeList) {
            HashMap<String, Object> item = new HashMap<String, Object>();
            item.put(Constants.KEY_ID, Utils.getInt(element.getAttribute(Constants.KEY_ID)));
            item.put(Constants.KEY_PRODUCT_NAME,
                element.getAttribute(Constants.KEY_PRODUCT_NAME));
            item.put(Constants.KEY_ICON,
                element.getAttribute(Constants.KEY_ICON));
            list.add(item);
        }

        /*
         * 往结果中追加两个Item
         * 兑换记录
         * 收入明细
         */

        //添加兑换记录
        HashMap<String, Object> item = new HashMap<String, Object>();
        item.put(Constants.KEY_ID, Constants.ID_EXCHANGE_RECORD);
        item.put(Constants.KEY_PRODUCT_NAME, context.getString(R.string.exchange_h));
        item.put(Constants.KEY_ICON, context.getResources().getDrawable(R.drawable.exchange_records));
        list.add(item);

        //添加收入明细
        item = new HashMap<String, Object>();
        item.put(Constants.KEY_ID, Constants.ID_EXCHANGE_INCOME);
        item.put(Constants.KEY_PRODUCT_NAME, context.getString(R.string.exchange_d));
        item.put(Constants.KEY_ICON, context.getResources().getDrawable(R.drawable.income));
        list.add(item);
        return list;
    }

    /**
     * 解析返利兑换物品
     */

    private static ArrayList<HashMap<String, Object>> parseExchangeGoods(
        Context context, XmlElement xmlDocument) {

        if (xmlDocument == null) {
            return null;
        }


        XmlElement root = xmlDocument.getChild("goods", 0);

        List<XmlElement> goodsList = root.getChildren("good");
        ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
        for (XmlElement element : goodsList) {
            HashMap<String, Object> item = new HashMap<String, Object>();
            item.put(Constants.KEY_ID, element.getAttribute(Constants.KEY_ID));
            item.put(Constants.KEY_PRODUCT_NAME,
                element.getAttribute(Constants.KEY_PRODUCT_NAME));
            item.put(Constants.KEY_ICON,
                element.getAttribute(Constants.KEY_ICON));
            item.put(Constants.KEY_COST, context.getString(R.string.pay_unit,
                Utils.convertCentToYuan(
                    element.getAttribute(Constants.KEY_COST))));
            item.put(Constants.KEY_STATUS,
                element.getAttribute(Constants.KEY_STATUS));
            list.add(item);
        }

        return list;
    }

    /**
     * 解析兑换记录明细
     */

    private static HashMap<String, Object> parseExchangeDetail(
        Context context, XmlElement xmlDocument) {

        if (xmlDocument == null) {
            return null;
        }

        HashMap<String, Object> result = new HashMap<String, Object>();
        XmlElement root = xmlDocument.getChild("exchanges", 0);
        result.put(Constants.KEY_TOTAL_SIZE,
            Utils.getInt(root.getAttribute(Constants.KEY_TOTAL_SIZE)));

        List<XmlElement> exchangeList = root.getChildren("exchange");

        ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
        for (XmlElement element : exchangeList) {
            HashMap<String, Object> item = new HashMap<String, Object>();
            item.put(Constants.KEY_PRODUCT_NAME,
                element.getAttribute(Constants.KEY_PRODUCT_NAME));
            item.put(Constants.KEY_ICON,
                element.getAttribute(Constants.KEY_ICON));
            item.put(Constants.KEY_COST, "-" + context.getString(R.string.pay_unit,
                Utils.convertCentToYuan(element.getAttribute(Constants.KEY_COST))));
            item.put(Constants.KEY_EXCHANGE_TIME, Utils.formatTime(Utils.getLong(
                element.getAttribute(Constants.KEY_EXCHANGE_TIME))));
            item.put(Constants.KEY_INFORMATION,
                element.getAttribute(Constants.KEY_INFORMATION));
            list.add(item);
        }
        result.put(Constants.KEY_TASK_LIST, list);
        return result;
    }

    /**
     * 解析收入明细
     */

    private static HashMap<String, Object> parseRewardDetail(
        Context context, XmlElement xmlDocument) {

        if (xmlDocument == null) {
            return null;
        }

        HashMap<String, Object> result = new HashMap<String, Object>();
        XmlElement root = xmlDocument.getChild("rewards", 0);
        result.put(Constants.KEY_TOTAL_SIZE,
            Utils.getInt(root.getAttribute(Constants.KEY_TOTAL_SIZE)));

        List<XmlElement> rewardList = root.getChildren("reward");
        if (rewardList == null) {
            return null;
        }

        ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
        for (XmlElement element : rewardList) {
            HashMap<String, Object> item = new HashMap<String, Object>();
            item.put(Constants.KEY_ID, element.getAttribute(Constants.KEY_ID));
            item.put(Constants.KEY_PRODUCT_NAME,
                element.getAttribute(Constants.KEY_PRODUCT_NAME));
            item.put(Constants.KEY_ICON,
                element.getAttribute(Constants.KEY_ICON));
            item.put(Constants.KEY_PAY, "+" + context.getString(R.string.pay_unit,
                Utils.convertCentToYuan(
                    element.getAttribute(Constants.KEY_PAY))));
            int status = Utils.getInt(
                element.getAttribute(Constants.KEY_STATUS));
            if (status == 0) {
                // 待审核
                item.put(Constants.KEY_STATUS,
                    context.getString(R.string.rebate_status_pending));
            } else {
                // 已获取
                item.put(Constants.KEY_STATUS,
                    context.getString(R.string.rebate_status_complete));
            }
            item.put(Constants.KEY_TYPE,
                element.getAttribute(Constants.KEY_TYPE)
                    + " : " +
                    element.getAttribute(Constants.KEY_PRODUCT_NAME));
            item.put(Constants.KEY_REWARD_TIME,
                Utils.formatTime(Utils.getLong(
                    element.getAttribute(Constants.KEY_REWARD_TIME))));
            list.add(item);
        }
        result.put(Constants.KEY_TASK_LIST, list);
        return result;
    }

    /**
     * 解析申请返利结果
     *
     * @param xmlDocument
     * @return
     */

    private static HashMap<String, Object> parseRequestReward(
        XmlElement xmlDocument) {

        if (xmlDocument == null) {
            return null;
        }

        HashMap<String, Object> result = new HashMap<String, Object>();
        XmlElement pay = xmlDocument.getChild(Constants.KEY_PAY, 0);
        XmlElement pkg = xmlDocument.getChild("pkg", 0);
        result.put(Constants.KEY_PACKAGE, pkg.getText());
        result.put(Constants.KEY_PAY, pay.getText());
        return result;
    }

    /**
     * 解析兑换结果
     */

    private static String parseReward(XmlElement xmlDocument) {

        if (xmlDocument == null) {
            return null;
        }

        XmlElement result = xmlDocument.getChild(Constants.KEY_STATUS, 0);
        return result.getText();
    }

    /**
     * 获取搜索推荐关键词
     */

    private static ArrayList<String> parseSearchRecommend(String doc) {

        if (TextUtils.isEmpty(doc)) {
            return null;
        }

        try {
            JSONArray array = new JSONArray(doc);
            int length = array.length();
            ArrayList<String> result = new ArrayList<String>();
            for (int i = length - 1; i >= 0; i--) {
                result.add(array.getJSONObject(i).getString("hotWords"));
            }
            return result;
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 解析推送消息
     */

    private static ArrayList<Notification> parsePushMessage(Context context,
        XmlElement xmlDocument) {

        if (xmlDocument == null) {
            return null;
        }

        List<XmlElement> messages = xmlDocument.getChildren("msg");

        if (messages == null || messages.size() == 0) {
            return null;
        }

        ArrayList<Notification> notifications = new ArrayList<Notification>();
        String updateTime = "";
        for (XmlElement message : messages) {

            int type = Utils.getInt(message.getChild("type", 0).getText());
            // intent类型 0:action 1:class 2:action + uri 3:action + uri + class

            Intent i = null;
            if (type == 0) {
                String action = message.getChild("action", 0).getText();
                i = new Intent(action);
            } else if (type == 1) {
                String className = message.getChild("class", 0).getText();
                try {
                    i = new Intent(context, Class.forName(className));
                } catch (ClassNotFoundException e) {
                    Utils.E("ClassNotFoundException", e);
                }
            } else if (type == 2) {
                String action = message.getChild("action", 0).getText();
                String uri = message.getChild("uri", 0).getText();
                i = new Intent(action, Uri.parse(uri));
            } else if (type == 3) {
                String action = message.getChild("action", 0).getText();
                String uri = message.getChild("uri", 0).getText();
                String className = message.getChild("class", 0).getText();
                try {
                    i = new Intent(action, Uri.parse(uri), context, Class.forName(className));
                } catch (ClassNotFoundException e) {
                    Utils.E("ClassNotFoundException", e);
                }
            }
            if (i == null) {
                continue;
            }

            List<XmlElement> params = message.getChildren("param");
            if (params != null) {
                for (XmlElement param : params) {
                    String key = param.getChild("key", 0).getText();
                    String classType = param.getChild("param_class", 0).getText();
                    String value = param.getChild("value", 0).getText();
                    if ("byte".equalsIgnoreCase(classType)) {
                        i.putExtra(key, Byte.parseByte(value));
                    } else if ("boolean".equalsIgnoreCase(classType)) {
                        i.putExtra(key, Boolean.parseBoolean(value));
                    } else if ("short".equalsIgnoreCase(classType)) {
                        i.putExtra(key, Short.parseShort(value));
                    } else if ("char".equalsIgnoreCase(classType)) {
                        // FIXME
                        i.putExtra(key, value);
                    } else if ("int".equalsIgnoreCase(classType)) {
                        i.putExtra(key, Integer.parseInt(value));
                    } else if ("long".equalsIgnoreCase(classType)) {
                        i.putExtra(key, Long.parseLong(value));
                    } else if ("float".equalsIgnoreCase(classType)) {
                        i.putExtra(key, Float.parseFloat(value));
                    } else if ("double".equalsIgnoreCase(classType)) {
                        i.putExtra(key, Double.parseDouble(value));
                    }
                }
            }

            updateTime = message.getChild("update_time", 0).getText();

            Notification notification = new Notification();
            notification.icon = R.drawable.notification_icon;
            notification.when = System.currentTimeMillis();
            notification.defaults = Notification.DEFAULT_LIGHTS;
            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, i,
                Notification.FLAG_AUTO_CANCEL);
            String title = message.getChild("text", 0).getText();
            notification.setLatestEventInfo(context,
                context.getString(R.string.notification_message), title, pendingIntent);
            notification.flags |= Notification.FLAG_AUTO_CANCEL;

            notifications.add(notification);
        }
        if (!TextUtils.isEmpty(updateTime)) {
            Session.get(context).setLastPushTime(updateTime);
        }
        xmlDocument.clear();
        return notifications;
    }

    /*
    * 标记已读
    */
    private static boolean parseMarkAsRead(XmlElement xmlDocument) {

        if (xmlDocument == null) {
            return false;
        }

        XmlElement productList = xmlDocument.getChild(Constants.KEY_PRODUCT, 0);
        if (productList != null) {
            return true;
        }
        xmlDocument.clear();
        return false;
    }

    /*
    * 获取已关注推荐专题
    */

    private static HashMap<String, Object> parseFllowedRecommend(Context context,
        XmlElement xmlDocument) {

        if (xmlDocument == null) {
            return null;
        }

        HashMap<String, Object> result = new HashMap<String, Object>();
        result.put(Constants.KEY_TOTAL_SIZE,
            Utils.getInt(xmlDocument.getAttribute(Constants.KEY_TOTAL_SIZE)));
        result.put(Constants.KEY_TOTAL_UNREAD,
            Utils.getInt(xmlDocument.getAttribute(Constants.KEY_TOTAL_UNREAD)));
        ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
        List<XmlElement> recommendList = xmlDocument.getChildren(Constants.KEY_RECOMMEND);
        if (recommendList != null) {
            for (XmlElement element : recommendList) {
                HashMap<String, Object> item = new HashMap<String, Object>();
                item.put(Constants.KEY_ID, element.getAttribute(Constants.KEY_ID));
                item.put(Constants.KEY_ICON_URL, element.getAttribute(Constants.KEY_ICON_URL));
                item.put(Constants.KEY_RECOMMEND_NAME,
                    element.getAttribute(Constants.KEY_RECOMMEND_NAME));
                item.put(Constants.KEY_DESCRIPTION, element.getAttribute(Constants.KEY_DESCRIPTION));
                item.put(Constants.KEY_UPDATE_TIME, context.getString(
                    R.string.recommendation_update_time, DateUtils.getRelativeTimeSpanString(
                    Utils.getLong(element.getAttribute(Constants.KEY_UPDATE_TIME)),
                    System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS,
                    DateUtils.FORMAT_ABBREV_RELATIVE)));
                item.put(Constants.KEY_LIKE, element.getAttribute(Constants.KEY_LIKE));
                item.put(Constants.KEY_DISLIKE, element.getAttribute(Constants.KEY_DISLIKE));
                item.put(Constants.KEY_USER, element.getAttribute(Constants.KEY_USER));
                item.put(Constants.KEY_FANS, element.getAttribute(Constants.KEY_FANS));
                item.put(Constants.KEY_EXPERIENCE, element.getAttribute(Constants.KEY_EXPERIENCE));

                int unread = Utils.getInt(element.getAttribute(Constants.KEY_UNREAD));
                item.put(Constants.KEY_UNREAD, unread);

                if (unread > 0) {
                    // 有用户未阅读的更新
                    parseProductListResult(context, element, item);
                }

                list.add(item);
            }
        }
        result.put(Constants.KEY_RECOMMEND_LIST, list);
        xmlDocument.clear();
        return result;
    }

    /*
    * 解析达人推荐的产品更新列表
    */
    private static void parseProductListResult(Context context,
        XmlElement parent, HashMap<String, Object> result) {
        List<XmlElement> productList = parent.getChildren(Constants.KEY_PRODUCT);
        if (productList == null) {
            return;
        }
        // 获取已经安装的应用列表
        Session session = Session.get(context);
        HashSet<String> installedApps = session.getInstalledApps();

        ArrayList<HashMap<String, Object>> productArray = new ArrayList<HashMap<String, Object>>();
        for (XmlElement element : productList) {
            HashMap<String, Object> item = new HashMap<String, Object>();
            item.put(Constants.KEY_PRODUCT_ID, element.getAttribute(Constants.KEY_PRODUCT_ID));
            String packageName = element.getAttribute(Constants.KEY_PRODUCT_PACKAGE_NAME);
            item.put(Constants.KEY_PRODUCT_PACKAGE_NAME, packageName);
            int price = Utils.getInt(element.getAttribute(Constants.KEY_PRODUCT_PRICE));
            String priceText = price == 0 ? context.getString(R.string.free) : context
                .getString(R.string.duihuanquan_unit, price);
            item.put(Constants.KEY_PRODUCT_PRICE, priceText);

            if (installedApps.contains(packageName)) {
                // 应用已经安装，显示已经安装的信息提示
                item.put(Constants.KEY_PRODUCT_DOWNLOAD, Constants.STATUS_INSTALLED);
            } else {
                // 应用未安装，显示正常信息提示
                item.put(Constants.KEY_PRODUCT_DOWNLOAD, Constants.STATUS_NORMAL);
            }

            item.put(Constants.KEY_PRODUCT_NAME, element
                .getAttribute(Constants.KEY_PRODUCT_NAME));
            item.put(Constants.KEY_PRODUCT_AUTHOR, element
                .getAttribute(Constants.KEY_PRODUCT_AUTHOR));
            item.put(Constants.KEY_PRODUCT_SUB_CATEGORY, element
                .getAttribute(Constants.KEY_PRODUCT_TYPE)
                + " > " + element.getAttribute(Constants.KEY_PRODUCT_SUB_CATEGORY));

            item.put(Constants.KEY_PRODUCT_PAY_TYPE, Utils.getInt(element
                .getAttribute(Constants.KEY_PRODUCT_PAY_TYPE)));
            item.put(Constants.KEY_PRODUCT_RATING, Utils.getInt(element
                .getAttribute(Constants.KEY_PRODUCT_RATING)) / 10.0f);
            item.put(Constants.KEY_PRODUCT_SIZE, StringUtils.formatSize(element
                .getAttribute(Constants.KEY_PRODUCT_SIZE)));
            item.put(Constants.KEY_PRODUCT_ICON_URL, element
                .getAttribute(Constants.KEY_PRODUCT_ICON_URL));
            item.put(Constants.KEY_PRODUCT_SHORT_DESCRIPTION, element
                .getAttribute(Constants.KEY_PRODUCT_SHORT_DESCRIPTION));

            String source = element.getAttribute(Constants.KEY_PRODUCT_SOURCE_TYPE);
            if (Constants.SOURCE_TYPE_GOOGLE.equals(source)) {
                item.put(Constants.KEY_PRODUCT_SOURCE_TYPE, context
                    .getString(R.string.leble_google));
            }
            productArray.add(item);
        }
        result.put(Constants.KEY_PRODUCT_LIST, productArray);
    }


    /*
    * 获取关注结果
    */
    private static boolean parseFllowResult(XmlElement xmlDocument) {

        if (xmlDocument == null) {
            return false;
        }

        XmlElement recommend = xmlDocument.getChild(Constants.KEY_RECOMMEND, 0);

        if (recommend != null) {
            String result = recommend.getAttribute(Constants.KEY_FOLLOW_FLAG);
            if ("1".equals(result)) {
                xmlDocument.clear();
                return true;
            }
        }
        xmlDocument.clear();
        return false;
    }

    /*
     * 获取精品应用推荐
     */
    private static boolean parseNotificationRecommend(Context context,
        XmlElement xmlDocument) {

        if (xmlDocument == null) {
            return false;
        }
        ArrayList<HashMap<String, Object>> result = null;

        List<XmlElement> products = xmlDocument.getChildren(Constants.KEY_PRODUCT);
        if (products != null) {
            result = new ArrayList<HashMap<String, Object>>();

            for (XmlElement element : products) {

                HashMap<String, Object> item = new HashMap<String, Object>();
                item.put(Constants.KEY_ID, element.getAttribute(Constants.KEY_ID));
                item.put(Constants.KEY_NOTIFICATION_RECOMMEND_TITLE,
                    element.getAttribute(Constants.KEY_NOTIFICATION_RECOMMEND_TITLE));
                item.put(Constants.KEY_DESCRIPTION, element.getAttribute(Constants.KEY_DESCRIPTION));
                item.put(Constants.KEY_UPDATE_TIME, element.getAttribute(Constants.KEY_UPDATE_TIME));
                item.put(Constants.KEY_NOTIFICATION_RECOMMEND_NID,
                    element.getAttribute(Constants.KEY_NOTIFICATION_RECOMMEND_NID));
                item.put(Constants.KEY_NOTIFICATION_RECOMMEND_RULE,
                    element.getAttribute(Constants.KEY_NOTIFICATION_RECOMMEND_RULE));
                item.put(Constants.KEY_NOTIFICATION_URL,
                    element.getAttribute(Constants.KEY_NOTIFICATION_URL));

                result.add(item);
            }

            DBUtils.insertPushItems(context, result);
        }
        xmlDocument.clear();
        return true;
    }

    /*
     * 获取所有分类列表
     */

    private static ArrayList<HashMap<String, Object>> parseAllCategory(XmlElement xmlDocument) {

        if (xmlDocument == null) {
            return null;
        }

        List<XmlElement> categorys = xmlDocument.getChildren(Constants.KEY_CATEGORY);
        ArrayList<HashMap<String, Object>> result = null;
        if (categorys != null) {
            result = new ArrayList<HashMap<String, Object>>();

            for (int i = 1; i < categorys.size(); i++) {
                XmlElement category = categorys.get(i);
                if(!"game".equalsIgnoreCase(category.getAttribute(Constants.KEY_CATEGORY_CODE))) {
                	continue;
                }
                HashMap<String, Object> item = new HashMap<String, Object>();
                item.put(Constants.KEY_CATEGORY_NAME, category
                    .getAttribute(Constants.KEY_CATEGORY_NAME));
                item.put(Constants.KEY_CATEGORY_ENNAME, category
                    .getAttribute(Constants.KEY_CATEGORY_ENNAME));
                item.put(Constants.KEY_CATEGORY_NAME, category
                    .getAttribute(Constants.KEY_CATEGORY_NAME));
                item.put(Constants.KEY_APP_COUNT, category.getAttribute(Constants.KEY_APP_COUNT));
                item.put(Constants.KEY_CATEGORY_ICON_URL, category
                    .getAttribute(Constants.KEY_CATEGORY_ICON_URL));

                String subCategoryText = category.getChild(Constants.KEY_SUB_CATEGORY, 0)
                    .getAttribute(Constants.KEY_CATEGORY_NAME)
                    + ", ";
                XmlElement category2 = category.getChild(Constants.KEY_SUB_CATEGORY, 1);
                if (category2 != null) {
                    subCategoryText += (category2.getAttribute(Constants.KEY_CATEGORY_NAME) + ", ");
                }
                XmlElement category3 = category.getChild(Constants.KEY_SUB_CATEGORY, 2);
                if (category3 != null) {
                    subCategoryText += (category3.getAttribute(Constants.KEY_CATEGORY_NAME) + ", ");
                }
                if (subCategoryText.length() > 0) {
                    subCategoryText = subCategoryText.substring(0, subCategoryText.length() - 2);
                }
                item.put(Constants.KEY_TOP_APP, subCategoryText);
                
				String subCategoryEnText = category.getChild(
						Constants.KEY_SUB_CATEGORY, 0).getAttribute(
						Constants.KEY_CATEGORY_ENNAME)
						+ ", ";
				if (category2 != null) {
					subCategoryEnText += (category2
							.getAttribute(Constants.KEY_CATEGORY_ENNAME) + ", ");
				}
				if (category3 != null) {
					subCategoryEnText += (category3
							.getAttribute(Constants.KEY_CATEGORY_ENNAME) + ", ");
				}
				if (subCategoryEnText.length() > 0) {
					subCategoryEnText = subCategoryEnText.substring(0,
							subCategoryEnText.length() - 2);
				}
				item.put(Constants.KEY_EN_TOP_APP, subCategoryEnText);

                List<XmlElement> subCategorys = category.getChildren(Constants.KEY_SUB_CATEGORY);
                ArrayList<HashMap<String, Object>> subCategoryList = new ArrayList<HashMap<String, Object>>();
                for (XmlElement element : subCategorys) {
                    HashMap<String, Object> subCategory = new HashMap<String, Object>();
                    subCategory.put(Constants.KEY_CATEGORY_ID, element
                        .getAttribute(Constants.KEY_CATEGORY_ID));
                    subCategory.put(Constants.KEY_CATEGORY_NAME, element
                        .getAttribute(Constants.KEY_CATEGORY_NAME));
                    subCategory.put(Constants.KEY_CATEGORY_ENNAME, element
                            .getAttribute(Constants.KEY_CATEGORY_ENNAME));
                    subCategory.put(Constants.KEY_APP_COUNT, element
                        .getAttribute(Constants.KEY_APP_COUNT));
                    subCategory.put(Constants.KEY_CATEGORY_ICON_URL, element
                        .getAttribute(Constants.KEY_CATEGORY_ICON_URL));
                    String app1 = element.getAttribute(Constants.KEY_APP_1);
                    String app2 = element.getAttribute(Constants.KEY_APP_2);
                    String app3 = element.getAttribute(Constants.KEY_APP_3);
                    String topApp = (TextUtils.isEmpty(app1) ? "" : app1 + ", ")
                        + (TextUtils.isEmpty(app2) ? "" : app2 + ", ")
                        + (TextUtils.isEmpty(app3) ? "" : app3 + ", ");
                    if (topApp.length() > 0) {
                        topApp = topApp.substring(0, topApp.length() - 2);
                    }
                    subCategory.put(Constants.KEY_TOP_APP, topApp);
                    subCategoryList.add(subCategory);
                }
                item.put(Constants.KEY_SUB_CATEGORY, subCategoryList);
                result.add(item);
            }

            // 展开第一个一级列表
            XmlElement firstCategory = categorys.get(0);
            List<XmlElement> firstSubCategorys = firstCategory
                .getChildren(Constants.KEY_SUB_CATEGORY);
            for (XmlElement element : firstSubCategorys) {
                HashMap<String, Object> item = new HashMap<String, Object>();
                item
                    .put(Constants.KEY_CATEGORY_ID, element
                        .getAttribute(Constants.KEY_CATEGORY_ID));
                item.put(Constants.KEY_CATEGORY_NAME, element
                    .getAttribute(Constants.KEY_CATEGORY_NAME));
                item.put(Constants.KEY_APP_COUNT, element.getAttribute(Constants.KEY_APP_COUNT));
                item.put(Constants.KEY_CATEGORY_ICON_URL, element
                    .getAttribute(Constants.KEY_CATEGORY_ICON_URL));
                String app1 = element.getAttribute(Constants.KEY_APP_1);
                String app2 = element.getAttribute(Constants.KEY_APP_2);
                String app3 = element.getAttribute(Constants.KEY_APP_3);
                String topApp = (TextUtils.isEmpty(app1) ? "" : app1 + ", ")
                    + (TextUtils.isEmpty(app2) ? "" : app2 + ", ")
                    + (TextUtils.isEmpty(app3) ? "" : app3 + ", ");
                if (topApp.length() > 0) {
                    topApp = topApp.substring(0, topApp.length() - 2);
                }
                item.put(Constants.KEY_TOP_APP, topApp);
                result.add(item);
            }
        }
        xmlDocument.clear();
        return result;
    }

    /*
     * 获取产品详细信息
     */
    private static Object parseProductDetail(XmlElement xmlDocument) {

        if (xmlDocument == null) {
            return null;
        }

        XmlElement product = xmlDocument.getChild(Constants.KEY_PRODUCT, 0);
        ProductDetail result = null;

        if (product != null) {
            result = new ProductDetail();
            result.setPid(product.getAttribute(Constants.KEY_PRODUCT_ID));
            result.setProductType(product.getAttribute(Constants.KEY_PRODUCT_TYPE));
            result.setName(product.getAttribute(Constants.KEY_PRODUCT_NAME));
            result.setPrice(Utils.getInt(product.getAttribute(Constants.KEY_PRODUCT_PRICE)));
            result.setPayCategory(Utils
                .getInt(product.getAttribute(Constants.KEY_PRODUCT_PAY_TYPE)));
            result.setRating(Utils.getInt(product.getAttribute(Constants.KEY_PRODUCT_RATING))
                / 10.0f);
            result.setIconUrl(product.getAttribute(Constants.KEY_PRODUCT_ICON_URL));
            result.setShotDes(product.getAttribute(Constants.KEY_PRODUCT_SHORT_DESCRIPTION));
            result.setAppSize(Utils.getInt(product.getAttribute(Constants.KEY_PRODUCT_SIZE)));
            result.setSourceType(product.getAttribute(Constants.KEY_PRODUCT_SOURCE_TYPE));
            result.setPackageName(product.getAttribute(Constants.KEY_PRODUCT_PACKAGE_NAME));
            result.setVersionName(product.getAttribute(Constants.KEY_PRODUCT_VERSION_NAME));
            result.setVersionCode(Utils.getInt(product
                .getAttribute(Constants.KEY_PRODUCT_VERSION_CODE)));
            result.setCommentsCount(Utils.getInt(product
                .getAttribute(Constants.KEY_PRODUCT_COMMENTS_COUNT)));
            result.setRatingCount(Utils.getInt(product
                .getAttribute(Constants.KEY_PRODUCT_RATING_COUNT)));
            result.setDownloadCount(Utils.getInt(product
                .getAttribute(Constants.KEY_PRODUCT_DOWNLOAD_COUNT)));
            result.setLongDescription(product.getAttribute(Constants.KEY_PRODUCT_LONG_DESCRIPTION));
            result.setAuthorName(product.getAttribute(Constants.KEY_PRODUCT_AUTHOR));
            result.setPublishTime(Utils.getInt(product
                .getAttribute(Constants.KEY_PRODUCT_PUBLISH_TIME)));
            final String[] screenShot = new String[5];
            screenShot[0] = product.getAttribute(Constants.KEY_PRODUCT_SCREENSHOT_1);
            screenShot[1] = product.getAttribute(Constants.KEY_PRODUCT_SCREENSHOT_2);
            screenShot[2] = product.getAttribute(Constants.KEY_PRODUCT_SCREENSHOT_3);
            screenShot[3] = product.getAttribute(Constants.KEY_PRODUCT_SCREENSHOT_4);
            screenShot[4] = product.getAttribute(Constants.KEY_PRODUCT_SCREENSHOT_5);
            result.setScreenshot(screenShot);
            final String[] screenShotLdpi = new String[5];
            screenShotLdpi[0] = product.getAttribute(Constants.KEY_PRODUCT_SCREENSHOT_LDPI_1);
            screenShotLdpi[1] = product.getAttribute(Constants.KEY_PRODUCT_SCREENSHOT_LDPI_2);
            screenShotLdpi[2] = product.getAttribute(Constants.KEY_PRODUCT_SCREENSHOT_LDPI_3);
            screenShotLdpi[3] = product.getAttribute(Constants.KEY_PRODUCT_SCREENSHOT_LDPI_4);
            screenShotLdpi[4] = product.getAttribute(Constants.KEY_PRODUCT_SCREENSHOT_LDPI_5);
            result.setScreenshotLdpi(screenShotLdpi);
            result.setUpReason(product.getAttribute(Constants.KEY_PRODUCT_UP_REASON));
            result.setUpTime(Utils.getLong(product.getAttribute(Constants.KEY_PRODUCT_UP_TIME)));
            result.setPermission(product.getAttribute(Constants.KEY_PRODUCT_PERMISSIONS));
            result.setRsaMd5(product.getAttribute(Constants.KEY_PRODUCT_RSA_MD5));
            result.setUpdateTime(Utils.getLong(product.getAttribute(Constants.KEY_UPDATE_TIME)));

            List<XmlElement> flags = product.getChildren("flag");
            if (flags != null) {
                for (XmlElement e : flags) {
                    String value = e.getText();
                    if ("1".equals(value)) {
                        result.isLocal = true;
                    } else if ("2".equals(value)) {
                        result.isClean = true;
                    } else if ("3".equals(value)) {
                        result.isFirst = true;
                    } else if ("4".equals(value)) {
                        result.isStar = true;
                    }
                }
            }
        }
        xmlDocument.clear();
        return result;
    }

    /**
     * 解析同步应用
     */

    private static Object parseSyncApps(XmlElement xmlDocument) {

        if (xmlDocument == null) {
            return null;
        }
        UpdateInfo updateInfo = new UpdateInfo();

        updateInfo.setUpdageLevel(Integer.valueOf(xmlDocument.getChild(
            Constants.EXTRA_UPDATE_LEVEL, 0).getText()));
        updateInfo.setVersionCode(Integer.valueOf(xmlDocument.getChild(
            Constants.EXTRA_VERSION_CODE, 0).getText()));
        updateInfo.setVersionName(xmlDocument.getChild(Constants.EXTRA_VERSION_NAME, 0).getText());
        updateInfo.setDescription(xmlDocument.getChild(Constants.EXTRA_DESCRIPTION, 0).getText());
        updateInfo.setApkUrl(xmlDocument.getChild(Constants.EXTRA_URL, 0).getText());

        xmlDocument.clear();
        return updateInfo;
    }

    /*
     * 解析我的评星结果
     */

    private static Object parseMyRating(XmlElement xmlDocument) {
        if (xmlDocument == null) {
            return null;
        }

        XmlElement element = xmlDocument.getChild(Constants.KEY_PRODUCT_RATING, 0);
        Object obj = null;
        if (element != null) {
            obj = element.getAttribute(Constants.KEY_VALUE);
        }
        xmlDocument.clear();
        return obj;
    }

    /*
     * 解析评论列表
     */
    private static Object parseComments(XmlElement xmlDocument) {
        if (xmlDocument == null) {
            return null;
        }
        HashMap<String, Object> result = null;
        XmlElement comments = xmlDocument.getChild(Constants.KEY_COMMENTS, 0);
        if (comments != null) {
            result = new HashMap<String, Object>();

            int totalSize = Utils.getInt(comments.getAttribute(Constants.KEY_TOTAL_SIZE));
            result.put(Constants.KEY_TOTAL_SIZE, totalSize);

            if (totalSize > 0) {
                ArrayList<HashMap<String, Object>> commentList = new ArrayList<HashMap<String, Object>>();
                List<XmlElement> children = comments.getChildren(Constants.KEY_COMMENT);

                if (children == null) {
                    return null;
                }
                for (XmlElement element : children) {
                    HashMap<String, Object> commentEntity = new HashMap<String, Object>();

                    commentEntity.put(Constants.KEY_COMMENT_ID, element
                        .getAttribute(Constants.KEY_COMMENT_ID));
                    commentEntity.put(Constants.KEY_COMMENT_AUTHOR, element
                        .getAttribute(Constants.KEY_COMMENT_AUTHOR));
                    commentEntity.put(Constants.KEY_COMMENT_BODY, element
                        .getAttribute(Constants.KEY_COMMENT_BODY));
                    long millis = Utils.getLong(element.getAttribute(Constants.KEY_COMMENT_DATE));
                    commentEntity.put(Constants.KEY_COMMENT_DATE, Utils.formatTime(millis));
                    commentList.add(commentEntity);
                }
                result.put(Constants.KEY_COMMENT_LIST, commentList);
            }
        }
        xmlDocument.clear();
        return result;
    }

    /*
     * 解析注册或者登录结果
     */

    private static HashMap<String, String> parseLoginOrRegisterResult(XmlElement xmlDocument) {

        if (xmlDocument == null) {
            return null;
        }

        HashMap<String, String> result = new HashMap<String, String>();
        result.put(Constants.KEY_USER_UID, xmlDocument.getChild(Constants.KEY_USER_UID, 0)
            .getText());
        result.put(Constants.KEY_USER_NAME, xmlDocument.getChild(Constants.KEY_USER_NAME, 0)
            .getText());
        result.put(Constants.KEY_USER_EMAIL, xmlDocument.getChild(Constants.KEY_USER_EMAIL, 0)
            .getText());
        xmlDocument.clear();
        return result;
    }
    
    /*
     * 解析注册或者登录结果
     */

    private static HashMap<String, String> parseThirdLoginResult(XmlElement xmlDocument) {

        if (xmlDocument == null) {
            return null;
        }

        HashMap<String, String> result = new HashMap<String, String>();
        result.put(Constants.KEY_USER_UID, xmlDocument.getChild(Constants.KEY_USER_UID, 0)
            .getText());
        xmlDocument.clear();
        return result;
    }

    /*
     * 解析应用列表
     */

    private static HashMap<String, Object> parseProductList(Context context,
        XmlElement xmlDocument, boolean isIgnoreStar) {

        if (xmlDocument == null) {
            return null;
        }
        final String IS_STAR_PRODUCT = "1";
        XmlElement products = xmlDocument.getChild(Constants.KEY_PRODUCTS, 0);
        HashMap<String, Object> result = null;
        ArrayList<HashMap<String, Object>> productArray = null;
        if (products != null) {

            // 获取已经安装的应用列表
            Session session = Session.get(context);
            HashSet<String> installedApps = session.getInstalledApps();

            List<XmlElement> productList = products.getChildren(Constants.KEY_PRODUCT);
            if (productList == null) {
                xmlDocument.clear();
                return null;
            }
            result = new HashMap<String, Object>();
            result.put(Constants.KEY_TOTAL_SIZE, Utils.getInt(products
                .getAttribute(Constants.KEY_TOTAL_SIZE)));
            result.put(Constants.KEY_END_POSITION, Utils.getInt(products
                .getAttribute(Constants.KEY_END_POSITION)));
            productArray = new ArrayList<HashMap<String, Object>>();
            for (XmlElement element : productList) {
                HashMap<String, Object> item = new HashMap<String, Object>();
                item.put(Constants.KEY_PRODUCT_ID, element.getAttribute(Constants.KEY_PRODUCT_ID));
                String packageName = element.getAttribute(Constants.KEY_PRODUCT_PACKAGE_NAME);
                item.put(Constants.KEY_PRODUCT_PACKAGE_NAME, packageName);
                String versionName = element.getAttribute(Constants.KEY_PRODUCT_VERSION_NAME);
                int versionCode = Utils.getInt(element.getAttribute(Constants.KEY_PRODUCT_VERSION_CODE));
                item.put(Constants.KEY_PRODUCT_VERSION_NAME, versionName);
                item.put(Constants.KEY_PRODUCT_VERSION_CODE, versionCode);
                String rsa = element.getAttribute(Constants.KEY_PRODUCT_RSA_MD5);
                item.put(Constants.KEY_PRODUCT_RSA_MD5, rsa);
                int price = Utils.getInt(element.getAttribute(Constants.KEY_PRODUCT_PRICE));
                CharSequence priceStyle = null;

                //如果不是免费的，就使其颜色变成橘黄色。
                if(price == 0){
                    priceStyle = context.getString(R.string.free);
                }else{
                    String priceText = context
                            .getString(R.string.duihuanquan_unit, price);
                    
                    priceStyle = new SpannableStringBuilder(priceText);
                    ((SpannableStringBuilder)priceStyle).setSpan(
                            new ForegroundColorSpan(context.getResources().getColor(
                                    R.color.orange_light)), 0, priceText.length(),
                            Spannable.SPAN_INCLUSIVE_INCLUSIVE);
                }
                
                item.put(Constants.KEY_PRODUCT_PRICE, priceStyle);
                boolean isStar = IS_STAR_PRODUCT.equals(element
                    .getAttribute(Constants.KEY_PRODUCT_IS_STAR)) ? true : false;
                if (isIgnoreStar) {
                    // 忽略星标
                    item.put(Constants.KEY_PRODUCT_IS_STAR, false);
                } else {
                    item.put(Constants.KEY_PRODUCT_IS_STAR, isStar);
                }

                if (installedApps.contains(packageName)) {

                    if (isIgnoreStar && !isStar) {
                        // 首页忽略已经安装的应用
                        continue;
                    }

                    // 应用已经安装，显示已经安装的信息提示
                    item.put(Constants.KEY_PRODUCT_DOWNLOAD, Constants.STATUS_INSTALLED);
                } else {
                    // 应用未安装，显示正常信息提示
                    item.put(Constants.KEY_PRODUCT_DOWNLOAD, Constants.STATUS_NORMAL);
                }

                item.put(Constants.KEY_PRODUCT_NAME, element
                    .getAttribute(Constants.KEY_PRODUCT_NAME));
                item.put(Constants.KEY_PRODUCT_AUTHOR, element
                    .getAttribute(Constants.KEY_PRODUCT_AUTHOR));
                item.put(Constants.KEY_PRODUCT_SUB_CATEGORY, element
                    .getAttribute(Constants.KEY_PRODUCT_TYPE)
                    + " > " + element.getAttribute(Constants.KEY_PRODUCT_SUB_CATEGORY));

                item.put(Constants.KEY_PRODUCT_PAY_TYPE, Utils.getInt(element
                    .getAttribute(Constants.KEY_PRODUCT_PAY_TYPE)));
                item.put(Constants.KEY_PRODUCT_RATING, Utils.getInt(element
                    .getAttribute(Constants.KEY_PRODUCT_RATING)) / 10.0f);
                item.put(Constants.KEY_PRODUCT_SIZE, StringUtils.formatSize(element
                    .getAttribute(Constants.KEY_PRODUCT_SIZE)));
                item.put(Constants.KEY_PRODUCT_ICON_URL, element
                    .getAttribute(Constants.KEY_PRODUCT_ICON_URL));
                item.put(Constants.KEY_PRODUCT_SHORT_DESCRIPTION, element
                    .getAttribute(Constants.KEY_PRODUCT_SHORT_DESCRIPTION));
                int downloadCount = Utils.getInt(element
                        .getAttribute(Constants.KEY_PRODUCT_DOWNLOAD_COUNT));
                String downloadText;
                String thousandSuffix = context.getString(R.string.thousand_suffix);
                if("thousands".equals(thousandSuffix)) {
//                	if (downloadCount > 1000) {
//                        downloadText = context.getString(R.string.label_download_count,
//                                context.getString(R.string.label_10_thousand, downloadCount / 1000.0f)) + thousandSuffix;
//                    } else {
                        downloadText = context.getString(R.string.label_download_count, String.valueOf(downloadCount));
//                    }
                } else {
                    if (downloadCount > 10000) {
                        downloadText = context.getString(R.string.label_download_count,
                                context.getString(R.string.label_10_thousand, downloadCount / 10000.0f)) + thousandSuffix;
                    } else {
                        downloadText = context.getString(R.string.label_download_count, String.valueOf(downloadCount));
                    }
                }
                item.put(Constants.KEY_PRODUCT_DOWNLOAD_COUNT, downloadText);

                item.put(Constants.KEY_PRODUCT_SOURCE_TYPE,
                        element.getAttribute(Constants.KEY_PRODUCT_SOURCE_TYPE));

                List<XmlElement> flags = element.getChildren("flag");
                if (flags != null) {
                    int mark = 0;
                    for (XmlElement e : flags) {
                        String value = e.getText();
                        if ("1".equals(value)) {
                            item.put(Constants.KEY_PRODUCT_LABEL_LOCAL, true);
                            mark = mark < 2 ? 2 : mark;
                        } else if ("2".equals(value)) {
                            item.put(Constants.KEY_PRODUCT_LABEL_CLEAN, true);
                            mark = mark < 1 ? 1 : mark;
                        } else if ("3".equals(value)) {
                            item.put(Constants.KEY_PRODUCT_LABEL_FIRST, true);
                            mark = mark < 4 ? 4 : mark;
                        } else if ("4".equals(value)) {
                            item.put(Constants.KEY_PRODUCT_LABEL_STAR, true);
                            mark = mark < 3 ? 3 : mark;
                        }
                    }
                    item.put(Constants.KEY_PRODUCT_CORNER, new CornerMark(mark));
                }

                productArray.add(item);
            }
            result.put(Constants.KEY_PRODUCT_LIST, productArray);
        }
        xmlDocument.clear();
        System.out.println("result = " + result);
        return result;
    }
    
    

    /*
     * 检查可更新产品列表
     */
    private static String parseUpgrade(Context context, XmlElement xmlDocument) {

        if (xmlDocument == null) {
            return "";
        }

        XmlElement products = xmlDocument.getChild(Constants.KEY_PRODUCTS, 0);
        String count = "";
        if (products != null) {
            List<XmlElement> productList = products.getChildren(Constants.KEY_PRODUCT);
            if (productList == null) {
                // 没有可更新的应用
                xmlDocument.clear();
                return count;
            }
            HashMap<String, UpgradeInfo> list = new HashMap<String, UpgradeInfo>();
            for (XmlElement element : productList) {
                UpgradeInfo info = new UpgradeInfo();
                info.pid = element.getAttribute(Constants.KEY_PRODUCT_ID);
                info.pkgName = element.getAttribute(Constants.KEY_PRODUCT_PACKAGE_NAME);
                info.versionName = element.getAttribute(Constants.KEY_PRODUCT_VERSION_NAME);
                info.versionCode = Utils.getInt(element
                        .getAttribute(Constants.KEY_PRODUCT_VERSION_CODE));
                info.signature = element.getAttribute(Constants.KEY_PRODUCT_RSA_MD5);
                info.sourceType = element.getAttribute(Constants.KEY_PRODUCT_SOURCE_TYPE);
                info.update = 0;
                list.put(info.pkgName, info);
            }
            count = String.valueOf(DBUtils.addUpdateProduct(context, list));
            interceptSystemApps(context, list);
        }
        xmlDocument.clear();
        return count;
    }

    /**
     * 拦截所有的没有可更新的系统应用<br>
     * 如果是系统应用并且没有更新的话，从安装列表中删除
     */
    private static void interceptSystemApps(Context context, HashMap<String, UpgradeInfo> upgrade) {
        Session session = Session.get(context);
        List<PackageInfo> all = session.getInstalledAppsInfo();
        synchronized (session.mPreloadInstalled) {
            for (PackageInfo info : all) {
                if (Utils.isSystemApp(info) && upgrade.containsKey(info.packageName)) {
                    loadSystemUpgrade(context, info);
                }
            }
        }
    }

    /**
     * 加载可更新的系统应用
     */
    private static void loadSystemUpgrade(Context context, PackageInfo info) {
        Session session = Session.get(context);
        HashMap<String, Object> item = new HashMap<String, Object>();
        item.put(Constants.KEY_PRODUCT_PACKAGE_NAME, info.packageName);
        item.put(Constants.KEY_PRODUCT_ICON_URL_LDPI, info);
        item.put(Constants.KEY_PRODUCT_NAME,
            info.applicationInfo.loadLabel(context.getPackageManager()));
        item.put(Constants.KEY_PRODUCT_VERSION_NAME,
            context.getString(R.string.current_version, info.versionName));
        item.put(Constants.KEY_PRODUCT_VERSION_CODE, info.versionCode);
        item.put(Constants.KEY_PRODUCT_RSA_MD5, StringUtils.toHexString(
                Utils.getFileSignatureMd5(info.applicationInfo.sourceDir), false));
        item.put(Constants.KEY_PRODUCT_IS_UPGRADE, true);
        session.mPreloadInstalled.put(info.packageName, item);
    }

    /*
    * 解析专题列表
    */

    private static ArrayList<HashMap<String, Object>> parseTopicList(Context context,
        XmlElement xmlDocument) {

        if (xmlDocument == null) {
            return null;
        }

        XmlElement topics = xmlDocument.getChild(Constants.KEY_TOPICS, 0);
        ArrayList<HashMap<String, Object>> topicArray = null;
        if (topics != null) {
            final String MUST_HAVE_ID = "5";
            List<XmlElement> topicList = topics.getChildren(Constants.KEY_TOPIC);
            topicArray = new ArrayList<HashMap<String, Object>>();
            for (XmlElement element : topicList) {
                HashMap<String, Object> item = new HashMap<String, Object>();

                String id = element.getAttribute(Constants.KEY_ID);
                if (MUST_HAVE_ID.equals(id)) {
                    // 装机必备不需要在这个列表中展示
                    continue;
                }
                item.put(Constants.KEY_ID, id);
                item.put(Constants.KEY_CATEGORY_NAME, element
                    .getAttribute(Constants.KEY_TOPIC_NAME));
                item.put(Constants.KEY_CATEGORY_ICON_URL, element
                    .getAttribute(Constants.KEY_TOPIC_ICON_LDPI));

                String app1 = element.getAttribute(Constants.KEY_APP_1);
                String app2 = element.getAttribute(Constants.KEY_APP_2);
                String app3 = element.getAttribute(Constants.KEY_APP_3);
                String description = app1 + ", ";
                if (!TextUtils.isEmpty(app2)) {
                    description += (app2 + ", ");
                }
                if (!TextUtils.isEmpty(app3)) {
                    description += (app3 + ", ");
                }
                if (description.length() > 1) {
                    description = description.substring(0, description.length() - 2);
                }
                item.put(Constants.KEY_TOP_APP, description);
                item.put(Constants.KEY_APP_COUNT, element.getAttribute(Constants.KEY_APP_COUNT));
                topicArray.add(item);
            }
        }
        xmlDocument.clear();
        return topicArray;
    }

    /*
     * 解析首页顶部推荐项列表
     */

    private static ArrayList<HashMap<String, Object>> parseTopRecommend(XmlElement xmlDocument) {

        if (xmlDocument == null) {
            return null;
        }

        List<XmlElement> recommends = xmlDocument.getAllChildren();
        ArrayList<HashMap<String, Object>> recommendList = null;
        if (recommends != null) {
            recommendList = new ArrayList<HashMap<String, Object>>();
            for (XmlElement element : recommends) {
                HashMap<String, Object> item = new HashMap<String, Object>();
                if (Constants.KEY_CATEGORY.equals(element.getName())) {
                    item.put(Constants.KEY_RECOMMEND_TYPE, Constants.KEY_CATEGORY);
                } else if (Constants.KEY_TOPIC.equals(element.getName())) {
                    item.put(Constants.KEY_RECOMMEND_TYPE, Constants.KEY_TOPIC);
                } else if (Constants.KEY_PRODUCT.equals(element.getName())) {
                    item.put(Constants.KEY_RECOMMEND_TYPE, Constants.KEY_PRODUCT);
                } else {
                    item.put(Constants.KEY_RECOMMEND_TYPE, -1);
                }
                item.put(Constants.KEY_ID, element.getAttribute(Constants.KEY_ID));
                item.put(Constants.KEY_PRODUCT_NAME,
                        element.getAttribute(Constants.KEY_PRODUCT_NAME));
                item.put(Constants.KEY_PRODUCT_PACKAGE_NAME,
                        element.getAttribute(Constants.KEY_PRODUCT_PACKAGE_NAME));
                item.put(Constants.KEY_RECOMMEND_ICON, element
                    .getAttribute(Constants.KEY_RECOMMEND_ICON));
                item.put(Constants.KEY_RECOMMEND_TITLE, element
                    .getAttribute(Constants.KEY_RECOMMEND_TITLE));
                recommendList.add(item);
            }
        }
        xmlDocument.clear();
        return recommendList;
    }

    /**
     * 获取同步购买列表
     */
    private static boolean parseSyncBuyLog(Context context, XmlElement xmlDocument) {

        if (xmlDocument == null) {
            return false;
        }

        XmlElement products = xmlDocument.getChild(Constants.KEY_PRODUCTS, 0);
        if (products == null) {
            xmlDocument.clear();
            return false;
        }
        List<XmlElement> productList = products.getChildren(Constants.KEY_PRODUCT);
        if (productList == null) {
            xmlDocument.clear();
            return false;
        }
        for (int i = 0, length = productList.size(); i < length; i++) {
            XmlElement product = products.getChild(Constants.KEY_PRODUCT, i);
            BuyLog buyLog = new BuyLog();
            buyLog.pId = product.getAttribute(Constants.KEY_PRODUCT_ID);
            buyLog.packageName = product.getAttribute(Constants.PRODUCT_PACKAGENAME);
            DBUtils.insertBuyLog(context, buyLog);
        }
        xmlDocument.clear();
        return true;
    }

    /**
     * 检查是否有新版本
     */

    private static Object parseCheckNewVersion(Context context, XmlElement xmlDocument) {
        if (xmlDocument == null) {
            return null;
        }

        int level = Utils.getInt(xmlDocument.getChild(Constants.EXTRA_UPDATE_LEVEL, 0).getText());

        if (level == 0) {
            xmlDocument.clear();
            return null;
        }

        UpdateInfo updateInfo = new UpdateInfo();
        updateInfo.setUpdageLevel(level);

        // 2011/8/17 BUG:2328 Fix NullPointerException
        XmlElement versionCode = xmlDocument.getChild(Constants.EXTRA_VERSION_CODE, 0);
        if (versionCode != null) {
            updateInfo.setVersionCode(Utils.getInt(versionCode.getText()));
        }
        XmlElement versionName = xmlDocument.getChild(Constants.EXTRA_VERSION_NAME, 0);
        if (versionName != null) {
            updateInfo.setVersionName(versionName.getText());
        }
        XmlElement description = xmlDocument.getChild(Constants.EXTRA_DESCRIPTION, 0);
        if (description != null) {
            updateInfo.setDescription(description.getText());
        }
        XmlElement apkUrl = xmlDocument.getChild(Constants.EXTRA_URL, 0);
        if (apkUrl != null) {
            updateInfo.setApkUrl(apkUrl.getText());
        }
        xmlDocument.clear();
        return updateInfo;
    }

    /*
     * 获取产品下载信息
     */

    private static DownloadItem parseDownloadInfo(XmlElement xmlDocument) {

        if (xmlDocument == null) {
            return null;
        }

        DownloadItem item = null;
        XmlElement downloadInfo = xmlDocument.getChild(Constants.KEY_DOWNLOAD_INFO, 0);
        if (downloadInfo != null) {
            item = new DownloadItem();
            item.pId = downloadInfo.getAttribute(Constants.KEY_PRODUCT_ID);
            item.packageName = downloadInfo.getAttribute(Constants.KEY_PRODUCT_PACKAGE_NAME);
            item.url = downloadInfo.getAttribute(Constants.KEY_PRODUCT_DOWNLOAD_URI);
            item.fileMD5 = downloadInfo.getAttribute(Constants.KEY_PRODUCT_MD5);
        }
        xmlDocument.clear();
        return item;
    }

    /*
     * 解析搜索热词列表
     */

    private static ArrayList<HashMap<String, Object>> parseSearchKeywords(
        Context context, XmlElement xmlDocument) {

        if (xmlDocument == null) {
            return null;
        }

        XmlElement keyList = xmlDocument.getChild(Constants.KEY_KEYLIST, 0);
        if (keyList == null) {
            return null;
        }

        int size = Utils.getInt(keyList.getAttribute(Constants.KEY_SIZE));
        ArrayList<HashMap<String, Object>> keywords = null;
        keywords = new ArrayList<HashMap<String, Object>>();
        List<XmlElement> keys = keyList.getAllChildren();
        int index = 1;
        for (XmlElement key : keys) {
            HashMap<String, Object> item = new HashMap<String, Object>();
            item.put(Constants.KEY_RANK, index++);

            String upOrDownNum = key.getAttribute(Constants.KEY_UP_DOWN);
            String keyword = key.getAttribute(Constants.KEY_TEXT);

            item.put(Constants.KEY_TEXT, keyword);
            int num = Utils.getInt(upOrDownNum);
            if (TextUtils.isEmpty(upOrDownNum)) {
                item.put(Constants.KEY_HAS_CHANGE, R.drawable.keyword_new);
                item.put(Constants.KEY_UP_DOWN, null);
            } else if (num > 0) {
                if ((index + num) > size) {
                    // 新进榜单
                    item.put(Constants.KEY_HAS_CHANGE, R.drawable.keyword_new);
                    item.put(Constants.KEY_UP_DOWN, null);
                } else {
                    item.put(Constants.KEY_HAS_CHANGE, R.drawable.keyword_up);
                    item.put(Constants.KEY_UP_DOWN, upOrDownNum);
                }
            } else if (num < 0) {
                item.put(Constants.KEY_HAS_CHANGE, R.drawable.keyword_down);
                item.put(Constants.KEY_UP_DOWN, Math.abs(num));
            } else {
                item.put(Constants.KEY_HAS_CHANGE, R.drawable.keyword_normal);
                item.put(Constants.KEY_UP_DOWN, null);
            }
            keywords.add(item);
        }
        xmlDocument.clear();
        return keywords;
    }

    /*
     * 解析搜索结果（BBS附件搜索）
     */

    private static HashMap<String, Object> parseBbsSearchResult(String body) {

        if (body == null) {
            return null;
        }
        HashMap<String, Object> result = null;
        try {
            JSONObject jsonBody = new JSONObject(body);
            result = new HashMap<String, Object>();
            result.put(Constants.KEY_TOTAL_SIZE, jsonBody.getInt("totalSize"));
            result.put(Constants.KEY_END_POSITION, jsonBody.getInt("endPosition"));
            JSONArray array = jsonBody.getJSONArray(Constants.KEY_JK_LIST);

            final int length = array.length();
            if (length > 0) {
                ArrayList<HashMap<String, Object>> topicList = new ArrayList<HashMap<String, Object>>();
                for (int i = 0; i < length; i++) {
                    HashMap<String, Object> map = new HashMap<String, Object>();
                    JSONObject item = array.getJSONObject(i);
                    map.put(Constants.SEARCH_RESULT_TITLE, String.valueOf(item
                        .get(Constants.KEY_SUBJECT)));
                    map.put(Constants.KEY_PLACEHOLDER, true);
                    topicList.add(map);
                    JSONArray subArray = item.getJSONArray(Constants.KEY_FILE_LIST);
                    for (int j = 0, len = subArray.length(); j < len; j++) {
                        HashMap<String, Object> subMap = new HashMap<String, Object>();
                        JSONObject subItem = subArray.getJSONObject(j);
                        subMap.put(Constants.KEY_PLACEHOLDER, false);
                        subMap.put(Constants.SEARCH_RESULT_TITLE, String.valueOf(subItem
                            .get(Constants.KEY_FILE_NAME)));
                        subMap.put(Constants.KEY_DOWN_URL, String.valueOf(subItem
                            .getString(Constants.KEY_DOWN_URL)));
                        topicList.add(subMap);
                    }
                }
                result.put(Constants.KEY_JK_LIST, topicList);
            }
        } catch (JSONException e) {
            Utils.D("have json exception when parse search result from bbs", e);
        }
        return result;
    }

    /*
     * 获取装机必备列表
     */

    private static Object parseGetRequired(Context context, XmlElement xmlDocument) {

        if (xmlDocument == null) {
            return null;
        }

        ArrayList<HashMap<String, Object>> result = null;
        List<XmlElement> productGroup = xmlDocument.getChildren(Constants.KEY_REQUIRED_CATEGORY);
        if (productGroup != null && productGroup.size() > 0) {

            result = new ArrayList<HashMap<String, Object>>();

            // 获取已经安装的应用列表
            Session session = Session.get(context);
            HashSet<String> installedApps = session.getInstalledApps();

            for (XmlElement group : productGroup) {

                // 分组信息
                HashMap<String, Object> groupItem = new HashMap<String, Object>();
                groupItem.put(Constants.INSTALL_PLACE_HOLDER, true);
                groupItem.put(Constants.INSTALL_APP_TITLE, group
                    .getAttribute(Constants.KEY_PRODUCT_NAME));
                List<XmlElement> productList = group.getChildren(Constants.KEY_PRODUCT);
                result.add(groupItem);

                if (productList == null || productList.size() == 0) {
                    continue;
                }

                // 分组下的产品列表信息
                for (XmlElement product : productList) {
                    HashMap<String, Object> productItem = new HashMap<String, Object>();
                    productItem.put(Constants.INSTALL_PLACE_HOLDER, false);
                    productItem.put(Constants.KEY_PRODUCT_ID, product
                        .getAttribute(Constants.KEY_PRODUCT_ID));
                    productItem.put(Constants.INSTALL_APP_LOGO, product
                        .getAttribute(Constants.KEY_PRODUCT_ICON_URL));
                    productItem.put(Constants.INSTALL_APP_TITLE, product
                        .getAttribute(Constants.KEY_PRODUCT_NAME));
                    productItem.put(Constants.INSTALL_APP_DESCRIPTION, product
                        .getAttribute(Constants.KEY_PRODUCT_SHORT_DESCRIPTION));
                    String packageName = product.getAttribute(Constants.KEY_PRODUCT_PACKAGE_NAME);
                    productItem.put(Constants.KEY_PRODUCT_PACKAGE_NAME, packageName);
                    if (installedApps.contains(packageName)) {
                        productItem.put(Constants.KEY_PRODUCT_IS_INSTALLED, true);
                    } else {
                        productItem.put(Constants.INSTALL_APP_IS_CHECKED, false);
                    }
                    result.add(productItem);
                }
            }
        }
        xmlDocument.clear();
        return result;
    }

    /*
     * 解析新的Splash页
     */

    private static SplashInfo parseNewSplash(XmlElement xmlDocument) {

        if (xmlDocument == null) {
            return null;
        }

        SplashInfo info = new SplashInfo();
        XmlElement url = xmlDocument.getChild(SplashInfo.URL, 0);
        if (url != null) {
            info.url = url.getText();
        }
        XmlElement time = xmlDocument.getChild(SplashInfo.TIMESTAMP, 0);
        if (time != null) {
            info.timestamp = Utils.getLong(time.getText());
        }
        xmlDocument.clear();
        return info;
    }

    /*
     * 解析支付历史
     */

    private static PayAndChargeLogs parseGetPayLog(Context context, XmlElement xmlDocument) {

        if (xmlDocument == null) {
            return null;
        }
        PayAndChargeLogs result = null;
        XmlElement logs = xmlDocument.getChild(Constants.KEY_PAY_LOGS, 0);
        if (logs != null) {
            result = new PayAndChargeLogs();
            result.endPosition = Utils.getInt(logs.getAttribute(Constants.KEY_END_POSITION));
            result.totalSize = Utils.getInt(logs.getAttribute(Constants.KEY_TOTAL_SIZE));

            List<XmlElement> consumes = logs.getChildren(Constants.KEY_PAY_CONSUME);
            getPayAndChargeLog(consumes, result, Constants.KEY_PAY_CONSUME);
            List<XmlElement> charges = logs.getChildren(Constants.KEY_PAY_CHARGE);
            getPayAndChargeLog(charges, result, Constants.KEY_PAY_CHARGE);

            List<XmlElement> buyApps = logs.getChildren(Constants.KEY_PAY_BUY_APP);
            getPayAndChargeLog(buyApps, result, Constants.KEY_PAY_BUY_APP);
        }
        xmlDocument.clear();
        return result;
    }

    /*
     * 读取consume,charge,buy_app标签
     */
    private static void getPayAndChargeLog(List<XmlElement> tags, PayAndChargeLogs result,
        String flag) {
        if (tags != null && tags.size() > 0) {
            for (XmlElement tag : tags) {
                PayAndChargeLog log = new PayAndChargeLog();
                log.name = tag.getAttribute(Constants.KEY_PAY_FLAG);
                log.id = Utils.getInt(tag.getAttribute(Constants.KEY_PAY_ORDER_ID));
                log.desc = tag.getAttribute(Constants.KEY_PAY_DESCRIPTION);
                log.time = Utils
                    .formatDate(Utils.getLong(tag.getAttribute(Constants.KEY_PAY_TIME)));
                log.payment = (int) Utils.getFloat(tag.getAttribute(Constants.KEY_PAY_MONEY));

                if (Constants.KEY_PAY_CONSUME.equals(flag)) {
                    log.type = PayAndChargeLog.TYPE_CONSUME;
                } else if (Constants.KEY_PAY_CHARGE.equals(flag)) {
                    log.type = PayAndChargeLog.TYPE_CHARGE;
                } else if (Constants.KEY_PAY_BUY_APP.equals(flag)) {
                    log.id = Utils.getInt(tag.getAttribute(Constants.KEY_PRODUCT_ID));
                    log.name = tag.getAttribute(Constants.KEY_PRODUCT_NAME);
                    log.iconUrl = tag.getAttribute(Constants.KEY_CATEGORY_ICON_URL);
                    log.type = PayAndChargeLog.TYPE_MARKET;
                    log.sourceType = Utils.getInt(tag
                        .getAttribute(Constants.KEY_PRODUCT_SOURCE_TYPE));
                }
                result.payAndChargeLogList.add(log);
            }
        }
    }

    /*
     * 同步充值卡信息
     */

    private static CardsVerifications parseSyncCardinfo(Context context, XmlElement xmlDocument) {

        if (xmlDocument == null) {
            return null;
        }
        CardsVerifications results = new CardsVerifications();
        results.version = Utils.getInt(xmlDocument.getAttribute(Constants.REMOTE_VERSION));

        List<XmlElement> cards = xmlDocument.getChildren(Constants.PAY_CARD);
        for (XmlElement card : cards) {
            CardsVerification subCard = new CardsVerification();
            subCard.name = card.getAttribute(Constants.KEY_USER_NAME);
            subCard.pay_type = card.getAttribute(Constants.PAY_TYPE);
            subCard.accountNum = Utils.getInt(card.getAttribute(Constants.ACCOUNT_LEN));
            subCard.passwordNum = Utils.getInt(card.getAttribute(Constants.PASSWORD_LEN));
            subCard.credit = card.getAttribute(Constants.PAY_CREDIT);
            results.cards.add(subCard);
        }
        xmlDocument.clear();
        return results;
    }

    /*
     * 解析充值结果
     */

    private static String parseChargeResult(XmlElement xmlDocument) {

        if (xmlDocument == null) {
            return null;
        }

        XmlElement result = xmlDocument.getChild(Constants.PAY_RESULT, 0);
        String res = null;
        if (result != null) {
            res = result.getAttribute(Constants.KEY_PAY_ORDER_ID);
        }
        xmlDocument.clear();
        return res;
    }

    /*
     * 解析充值结果(按订单号)
     */
    private static int parseQueryChargeResultByOderID(XmlElement xmlDocument) {

        if (xmlDocument == null) {
            return 0;
        }

        XmlElement result = xmlDocument.getChild(Constants.PAY_RESULT, 0);
        int res = 0;
        if (result != null) {
            res = Utils.getInt(result.getAttribute(Constants.KEY_PAY_STATUS));
        }
        xmlDocument.clear();
        return res;
    }

    /*
     * 解析查询余额
     */

    private static String parseGetBalance(XmlElement xmlDocument) {

        if (xmlDocument == null) {
            return null;
        }

        XmlElement result = xmlDocument.getChild(Constants.RESULT, 0);
        String res = null;
        if (result != null) {
            res = result.getText();
        }
        xmlDocument.clear();
        return res;
    }

    /*
     * 解析支付宝订单结果
     */

    private static JSONObject parseGetAlipayOrderInfo(String in) throws JSONException {
        byte[] data = Base64.decodeBase64(in);
        return new JSONObject(new String(new Crypter().decrypt(data,
            SecurityUtil.SECRET_KEY_HTTP_CHARGE_ALIPAY)));
    }

    /*
     * 解析客户端Log的级别
     */

    @SuppressWarnings("unchecked")
    private static HashMap<String, String> parseLogLevel(String in) throws JSONException {

        JSONObject body = new JSONObject(in);
        Iterator<String> keys = body.keys();
        HashMap<String, String> result = new HashMap<String, String>();
        while (keys.hasNext()) {
            String key = keys.next();
            result.put(key, body.getString(key));
        }
        return result;
    }

    /*
     * 解析提交Log结果
     */
    private static boolean parseSubmitLog(String in) throws JSONException {

        JSONObject body = new JSONObject(in);
        String result = body.getString("result");
        if ("success".equalsIgnoreCase(result)) {
            return true;
        }
        return false;
    }

    /*
     * 解析玩家推荐列表
     */

    private static Object parseMasterRecommend(Context context, XmlElement xmlDocument) {
        if (xmlDocument == null) {
            return null;
        }

        HashMap<String, Object> result = new HashMap<String, Object>();
        result.put(Constants.KEY_TOTAL_SIZE,
            Utils.getInt(xmlDocument.getAttribute(Constants.KEY_TOTAL_SIZE)));
        ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
        List<XmlElement> recommendList = xmlDocument.getChildren(Constants.KEY_RECOMMEND);
        if (recommendList != null) {
            for (XmlElement element : recommendList) {
                HashMap<String, Object> item = new HashMap<String, Object>();
                item.put(Constants.KEY_ID, element.getAttribute(Constants.KEY_ID));
                item.put(Constants.KEY_ICON_URL, element.getAttribute(Constants.KEY_ICON_URL));
                item.put(Constants.KEY_RECOMMEND_NAME,
                    element.getAttribute(Constants.KEY_RECOMMEND_NAME));
                item.put(Constants.KEY_DESCRIPTION, element.getAttribute(Constants.KEY_DESCRIPTION));
                item.put(Constants.KEY_UPDATE_TIME, context.getString(
                    R.string.recommendation_update_time, DateUtils.getRelativeTimeSpanString(
                    Utils.getLong(element.getAttribute(Constants.KEY_UPDATE_TIME)),
                    System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS,
                    DateUtils.FORMAT_ABBREV_RELATIVE)));
                item.put(Constants.KEY_LIKE, element.getAttribute(Constants.KEY_LIKE));
                item.put(Constants.KEY_DISLIKE, element.getAttribute(Constants.KEY_DISLIKE));
                item.put(Constants.KEY_USER, element.getAttribute(Constants.KEY_USER));
                item.put(Constants.KEY_FANS, element.getAttribute(Constants.KEY_FANS));
                item.put(Constants.KEY_EXPERIENCE, element.getAttribute(Constants.KEY_EXPERIENCE));

                list.add(item);
            }
        }
        result.put(Constants.KEY_RECOMMEND_LIST, list);
        xmlDocument.clear();
        return result;
    }

    /*
     * 解析详细页 发现tab，收录应用玩家列表
     */

    private static Object parseMasterContains(Context context, XmlElement xmlDocument) {
        if (xmlDocument == null) {
            return null;
        }
        HashMap<String, Object> result = new HashMap<String, Object>();
        ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
        List<XmlElement> recommendList = xmlDocument.getChildren(Constants.KEY_RECOMMEND);
        if (recommendList != null) {
            for (XmlElement element : recommendList) {
                HashMap<String, Object> item = new HashMap<String, Object>();
                item.put(Constants.KEY_ID, element.getAttribute(Constants.KEY_ID));
                item.put(Constants.KEY_ICON_URL, element.getAttribute(Constants.KEY_ICON_URL));
                item.put(Constants.KEY_RECOMMEND_NAME,
                    element.getAttribute(Constants.KEY_RECOMMEND_NAME));
                item.put(Constants.KEY_DESCRIPTION, element.getAttribute(Constants.KEY_DESCRIPTION));
                item.put(Constants.KEY_LIKE, element.getAttribute(Constants.KEY_LIKE));
                item.put(Constants.KEY_DISLIKE, element.getAttribute(Constants.KEY_DISLIKE));
                item.put(Constants.KEY_USER, element.getAttribute(Constants.KEY_USER));
                item.put(Constants.KEY_FANS, element.getAttribute(Constants.KEY_FANS));
                item.put(Constants.KEY_EXPERIENCE, element.getAttribute(Constants.KEY_EXPERIENCE));
                list.add(item);
            }
        }
        result.put(Constants.KEY_MASTER_CONTAINS_LIST, list);
        xmlDocument.clear();
        return result;
    }

    /*
    * 解析玩家推荐主题的讨论列表
    */

    private static Object parseGetDiscuss(XmlElement xmlDocument) {

        if (xmlDocument == null) {
            return null;
        }

        HashMap<String, Object> result = null;
        XmlElement comments = xmlDocument.getChild(Constants.KEY_DISCUSSES, 0);
        if (comments != null) {
            result = new HashMap<String, Object>();

            int totalSize = Utils.getInt(comments.getAttribute(Constants.KEY_TOTAL_SIZE));
            result.put(Constants.KEY_TOTAL_SIZE, totalSize);

            if (totalSize > 0) {
                ArrayList<HashMap<String, Object>> commentList = new ArrayList<HashMap<String, Object>>();
                List<XmlElement> children = comments.getChildren(Constants.KEY_DISCUSS);
                for (XmlElement element : children) {
                    HashMap<String, Object> commentEntity = new HashMap<String, Object>();
                    commentEntity.put(Constants.KEY_DISCUSS_ID,
                        element.getAttribute(Constants.KEY_DISCUSS_ID));
                    commentEntity
                        .put(Constants.KEY_DISCUSS_AUTHOR,
                            Constants.STATUS_IS_OWNER.equals(element
                                .getAttribute(Constants.KEY_DISCUSS_IS_OWNER)) ? (element
                                .getAttribute(Constants.KEY_DISCUSS_AUTHOR) + Constants.LABLE_OWNER)
                                : element.getAttribute(Constants.KEY_DISCUSS_AUTHOR));
                    long millis = Utils.getLong(element.getAttribute(Constants.KEY_DISCUSS_DATE));
                    commentEntity.put(Constants.KEY_COMMENT_DATE, Utils.formatTime(millis));
                    commentEntity.put(Constants.KEY_DISCUSS_CONTENT,
                        element.getAttribute(Constants.KEY_DISCUSS_CONTENT));
                    commentEntity.put(Constants.KEY_DISCUSS_IS_OWNER,
                        element.getAttribute(Constants.KEY_DISCUSS_IS_OWNER));
                    commentList.add(commentEntity);
                }
                result.put(Constants.KEY_COMMENT_LIST, commentList);
            }
        }
        xmlDocument.clear();
        return result;
    }

    /*
     * 解析玩家推荐评级
     */

    private static String parseRecommendRating(XmlElement xmlDocument) {

        if (xmlDocument == null) {
            return null;
        }

        XmlElement rating = xmlDocument.getChild(Constants.KEY_RATING, 0);
        String res = null;
        if (rating != null) {
            res = rating.getAttribute(Constants.KEY_VALUE);
        }
        xmlDocument.clear();
        return res;
    }

    /*
    * 解析首页的达人推荐专题
    */

    private static Object parseHomeMasterRecommend(Context context, XmlElement xmlDocument) {

        if (xmlDocument == null) {
            return null;
        }

        int result = Utils.getInt(xmlDocument.getAttribute(Constants.KEY_TOTAL_SIZE));
        if (result <= 0) {
            xmlDocument.clear();
            return null;
        }

        ArrayList<HashMap<String, Object>> list = null;
        List<XmlElement> recommendList = xmlDocument.getChildren(Constants.KEY_RECOMMEND);
        if (recommendList != null && recommendList.size() > 0) {

            list = new ArrayList<HashMap<String, Object>>();
            for (XmlElement element : recommendList) {
                HashMap<String, Object> item = new HashMap<String, Object>();
                item.put(Constants.KEY_ID, element.getAttribute(Constants.KEY_ID));
                item.put(Constants.KEY_ICON_URL, element.getAttribute(Constants.KEY_ICON_URL));
                item.put(Constants.KEY_RECOMMEND_NAME,
                    element.getAttribute(Constants.KEY_RECOMMEND_NAME));
                item.put(Constants.KEY_DESCRIPTION, element.getAttribute(Constants.KEY_DESCRIPTION));
                item.put(Constants.KEY_UPDATE_TIME, context.getString(
                    R.string.recommendation_update_time, DateUtils.getRelativeTimeSpanString(
                    Utils.getLong(element.getAttribute(Constants.KEY_UPDATE_TIME)),
                    System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS,
                    DateUtils.FORMAT_ABBREV_RELATIVE)));
                item.put(Constants.KEY_LIKE, element.getAttribute(Constants.KEY_LIKE));
                item.put(Constants.KEY_DISLIKE, element.getAttribute(Constants.KEY_DISLIKE));
                item.put(Constants.KEY_FANS, element.getAttribute(Constants.KEY_FANS));
                item.put(Constants.KEY_USER, element.getAttribute(Constants.KEY_USER));
                item.put(Constants.KEY_PIC_URL, element.getAttribute(Constants.KEY_PIC_URL));
                list.add(item);
            }
        }
        xmlDocument.clear();
        return list;
    }


    /**
     * 解析分类标签列表
     * @param context
     * @param xmlDocument
     */
    private static Object parseCategoryTags(Context context, XmlElement xmlDocument){

        if(xmlDocument == null){
            return null;
        }

        List<XmlElement> groupList = xmlDocument.getAllChildren();
        List<HashMap<String, Object>> result = new ArrayList<HashMap<String,Object>>(groupList.size());

        for (XmlElement element : groupList) {
            HashMap<String, Object> item = new HashMap<String, Object>();
            item.put(Constants.KEY_GROUP_ID, element.getAttribute(Constants.KEY_GROUP_ID));
            item.put(Constants.KEY_GROUP_NAME, element.getAttribute(Constants.KEY_GROUP_NAME));
            item.put(Constants.KEY_APP_COUNT, element.getAttribute(Constants.KEY_APP_COUNT));
            List<TagsInfo> tagsList = new ArrayList<TagsInfo>();
            for (XmlElement sub : element.getChildren(Constants.KEY_TAG)) {
                tagsList.add(new TagsInfo()
                        .setTagId(sub.getAttribute(Constants.KEY_TAG_ID))
                        .setTagName(sub.getAttribute(Constants.KEY_TAG_NAME))
                        .setAppCount(sub.getAttribute(Constants.KEY_APP_COUNT)));
            }
            item.put(Constants.KEY_TAGS, tagsList);
            result.add(item);
        }

        return result;
    }

    /**
     * 解析标签详情
     * @param context
     * @param xmlDocument
     * @return
     */
    private static Object parseTagsDetail(Context context, XmlElement xmlDocument){

        if(xmlDocument == null){
            return null;
        }

        return parseProductList(context,xmlDocument,true);
    }

    /**
     * 解析详情页中的标签
     * @param context
     * @param xmlDocument
     * @return
     */
    private static Object parseTagsInDetail(Context context, XmlElement xmlDocument) {

        if (xmlDocument == null) {
            return null;
        }
        ArrayList<TagsInfo> tagsInfo = new ArrayList<TagsInfo>();

        XmlElement tags = xmlDocument.getChild(Constants.KEY_TAGS, 0);

        if (tags == null) {
            //without data, what else can we do?
            return null;
        }


        List<XmlElement> subList = tags.getChildren(Constants.KEY_TAG);

        if (subList == null || subList.size() == 0) {
            // without data, what else can we do?
            return null;
        }

        for (XmlElement sub : subList) {
            tagsInfo.add(new TagsInfo()
                    .setTagId(sub.getAttribute(Constants.KEY_TAG_ID))
                    .setTagName(sub.getAttribute(Constants.KEY_TAG_NAME))
                    .setAppCount(sub.getAttribute(Constants.KEY_APP_COUNT)));
        }

        return tagsInfo.size() == 0 ? null : tagsInfo;
    }
}